世界太小,仍没走遍;世界太大,依然偶遇

python学习笔记(一)——入门

     python很多人都非常熟悉,而我作为后知后觉者,虽然慢人一步,但是学习永远不会晚。其实作为shell,不管是perl还是ruby、powershell等,语法很相似的,我以前没接触过python,现在从最基础的学起,当然对于非常简单的并没有详细记录,简单的准备记录下应该注意的地方。虽然python3.X的shell工具已经出来了,但是相关教程好像没找到,而且与python2.x语法好多不兼容。所以我的学习环境是python shell2.7,也是目前最稳定和常用的版本吧。

  娱乐阶段:

  学习python之前,先来看看python的设计哲学,我觉得Guido van Rossum一定是个有趣的人,能将设计思想展现在python解释器中,呵呵。输入import this 命令:

Python 2.7.3 (default, Apr 10 2012, 23:31:26) [MSC v.1500 32 bit (Intel)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> import this
The Zen of Python, by Tim Peters

Beautiful is better than ugly.       优美胜于丑陋
Explicit is better than implicit.    明了胜于晦涩
Simple is better than complex.       简单胜过复杂
Complex is better than complicated.  复杂胜过凌乱
Flat is better than nested.      扁平胜于嵌套
Sparse is better than dense.      间隔胜于紧凑
Readability counts.           可读性很重要
Special cases aren't special enough to break the rules.   即使假借特例的实用性之名,也不违背这些规则
Although practicality beats purity.   虽然实用性次于纯度
Errors should never pass silently.    错误不应该被无声的忽略
Unless explicitly silenced.        除非明确的沉默       
In the face of ambiguity, refuse the temptation to guess. 当存在多种可能时,不要尝试去猜测
There should be one-- and preferably only one --obvious way to do it. 应该有一个,最好只有一个,明显能做到这一点
Although that way may not be obvious at first unless you're Dutch.虽然这种 方式可能不容易,除非你是python之父
Now is better than never.    现在做总比不做好
Although never is often better than *right* now.  虽然过去从未比现在好
If the implementation is hard to explain, it's a bad idea.  如果这个实现不容易解释,那么它肯定是坏主意
If the implementation is easy to explain, it may be a good idea.   如果这个实现容易解释,那么它很可能是个好主意
Namespaces are one honking great idea -- let's do more of those!  命名空间是一种绝妙的理念,应当多加利用
>>> 

  哈哈,和一般的语言不同,在“hello world”程序开始之前,它还有一番人生哲学啊。

    初步入门:

    第一个python程序:(和其他脚本一样,可以按tab键快速选择)

>>> print "hello world"    ==>print是一个函数
hello world
>>> 

    这个在python3.0的解释器中运行是错误的,应该写成:print("hello world"),不管这些,以下均是2.X版本下。

  基础知识:

  交互式python解释器可以当非常强大的计算器使用 

>>> 1+1
2
>>> 1/2   ==>和其他语言一样,不做任何处理的情况下,这个是取整
0
>>> 1.0/2  ==>将任意一个数写成浮点形式,则结果会与精度最大的保持一致
0.5
>>> 1./2   ==>单独写个小数点也行
0.5
>>> 1//2   ==>   //这个符号是专门取整的
0
>>> 

         假如不想每次都要这么费劲一下,我就想在python里执行普通的除法,有办法:

>>> from __future__ import division   ==>注意future左右是两个下划线
>>> 1/2
0.5
>>> 1//2   ==>在这种情况下你反而想取整数部分了,使用//
>>> 0
>>>1.//2
>>>0.0

      长整型和进制:

>>> 958346283662845  ==>2.2版本以前是不能处理长整型的,范围是-2147483648~2147483647
958346283662845L   ==>L表示长整型,而且是大写
>>> 0xAF  ==>16进制
175
>>> 010   ==>8进制  (010首数字是0,表8进制)
8
>>> 

  获取用户输入:

>>> x=input("x=")
x=3
>>> y=input("y=")
y=4
>>> x*y
12

     函数:

>>> pow(2,3)   ==>求幂函数
8
>>> 2**3
8
>>> abs(-10)   ==>取绝对值
10
>>> round(5/2) ==>这里是先算5/2,即2,所以round(2)=2.0
2.0
>>> round(2.5) ==>把浮点数四舍五入为最接近的整数值
3.0
>>> floor(32.9) ==>取为不大于该数的最大整数
32

  模块:

>>> floor(23.5)
==>出错了
Traceback (most recent call last):   
  File "<pyshell#29>", line 1, in <module>
    floor(23.5)
NameError: name 'floor' is not defined
>>> import math   ==>引入模块math
>>> math.floor(23.5)
23.0
>>> int(math.floor(23.5))  ==>转换为整数
23
>>> 

   那我不想每次都输入math.来调用相应函数,如下写法:

>>> from math import floor
>>> floor(3.2)
3.0

  cmath和复数:

  在高中的时候有复数的预算,比如对一个复数取平方根,python提供了对复数处理的机制,但是要引入cmath模块。

>>> sqrt(-9)

Traceback (most recent call last):
  File "<pyshell#35>", line 1, in <module>
    sqrt(-9)
NameError: name 'sqrt' is not defined
>>> import math   ==>引入math模块也无效
>>> math.sqrt(-9)

Traceback (most recent call last):
  File "<pyshell#37>", line 1, in <module>
    math.sqrt(-9)
ValueError: math domain error
>>> import cmath  ==>引入cmath模块
>>> cmath.sqrt(-9)
3j
>>> (1+3j)*(9-2j)  ==>还可以进行计算
(15+25j)
>>> 

(__future__这个模块比较特别,它可以导入那些在未来会成为标准python组成的新特性)

  保存并执行程序:

  现在建一个python文件,扩展名是.py,把 print "hello python!"写入,双击,我们看到的是一闪而过的一个黑框,我记得在执行C#窗体程序的时候也会出现这种情况,只要在主程序结尾加上"Console.ReadKey()"就行了,这里也是,要给控制台一个提醒输入的机会,不然运行完就退出了,在结尾加一个语句:raw_input()。再双击即可弹出“hello python!”

执行这个文件hello.py
name=raw_input ("what is you name:")
print "hello "+name +"!"
raw_input()

      字符串:

>>> "hello python!"   ==>双引号会把原字符串按原样显示
'hello python!'
>>> "we'll go shopping!"
"we'll go shopping!"
>>> 'we'll go shopping!'
SyntaxError: invalid syntax
>>> 'we\'ll go shopping!'   ==>转义单引号
"we'll go shopping!"
>>> "\"hello,python!\" she said"   ==>字符串本身有双引号的情况
'"hello,python!" she said'
>>>"hello " + "python!"   ==>字符串拼接
'hello python!'

       str & repr:

  您可能发现了,不用print打印出的字符串显示出来的时候会被单引号括起来。所有通过python打印的字符串是被引号括起来的,这是因为python打印值的时候会保持该值在代码中的状态,而不是你希望用户看到的状态。

>>> print "hello world"
hello world
>>> print 'hello world'
hello world
>>> "hello world"
'hello world'
>>> 'hello world'
'hello world'
>>> print 10000L
10000
>>> 10000L
10000L
>>> 

     这里讨论的实际是值转换成字符串的两种机制,

   str函数:会把值转换为较理性的字符串,以便用户可以理解

   repr函数:会创建一个字符串,以合法的python表达式的形式表示值。

>>> print repr("hello python!")
'hello python!'
>>> print repr(100000L)
100000L
>>> print str("hello python!")    ==>显然,用户更希望看到的是str函数处理后的结果
hello python!
>>> print str(10000L)
10000
>>> 

    其实python有时候也没有这么智能,在高级语言中,好像数字有时候可以自动转换为字符串型

>>> age=22
>>> print "my age is "+ age

Traceback (most recent call last):
  File "<pyshell#72>", line 1, in <module>
    print "my age is "+ age
TypeError: cannot concatenate 'str' and 'int' objects
>>> print "my age is "+ str(age)
my age is 22
>>> 

   input & raw_input

      这样,我们先运行两个脚本,代码如下:

name=input("please input your name:")
print "hello,"+name

另一个脚本是将上述input改为raw_input

  运行会发现,第一个出错。其实不运行脚本也行,我么直接在解释器里运行命令吧!

>>> name =input("please input name:")
please input name:Jay

Traceback (most recent call last):
  File "<pyshell#74>", line 1, in <module>
    name =input ("please input name:")
  File "<string>", line 1, in <module>
NameError: name 'Jay' is not defined
>>> name =raw_input ("please input name:")
please input name:Jay

     其实你只要在input那个下面输入的字符串加上引号就行了,这就是原因。input会假设用户输入的是python的合法表达式,当然以字符串作为输入的名字肯定没有问题,但是要求用户每次输入一个东西还需要加引号,这不太友好。

  想反,raw_input函数会把所有的输入当做原始数据,然后自动将其放入字符串中,所以不会出错,所以我们应尽可能使用 raw_input()

     长字符串

  如果需要写一个很长的字符串,它需要跨多行,可以使用三个单引号,强制换行用反斜杠\

>>> '''asdgh
agjaw
ag'''
'asdgh\nagjaw\nag'
>>> 1+5+\
      4+6
16
>>>

      python中对多个反斜杠(路径中常用)转义除了加\,可以在整个字串的前面加r

>>> print 'c:\temp\test.txt'   
c:    emp    est.txt      ==>\t是制表符,所以会将\t作为一个制表符显示
>>> print 'c:\\temp\\test.txt'   ==>用传统的\转义
c:\temp\test.txt
>>> print r'c:\temp\test.txt'    ==>在前面加r转义
c:\temp\test.txt
>>> 

     

      常用的函数:abs(number)、cmath.sqrt(number)、float(object)、help()、input(prompt)、int(object)、long(object)、math.ceil(number)(返回上入整数)、math.floor(number)(返回下舍整数)、pow(x,y)、raw_input(prompt)、repr(object)、str(object)、round(number[.ndigits])

     

     以上知识非常基础,刚入门,如有错误,请指出,谢谢!

 

      

 

posted @ 2013-03-30 18:21  单曲荨环  阅读(10359)  评论(6编辑  收藏  举报
好好学习天天向上的女少年