Python Chapter 1 基础知识

数字和表达式

Note: Python不需要用分号结束,如果喜欢的话,也可以加上分号,但不会有任何作用(除非同一行有更多代码).

如果只希望Python执行普通的除法,那么可以在程序前加上以下语句:

from __future__ import division

这样当Python执行1/2时,会按照普通除法来操作,输出0.但是单斜线不在用作整除了,我们可以使用双斜线'//'实现整除操作.

>>> 1 // 2
0
>>> 1.0 // 2.0
0.0

Python的取余运算符'%',也可以作用于浮点数.

>>> 2.75 % 0.5
0.25

Python的幂(乘方)运算符'**':

>>> 2 ** 3
8
>>> -3 ** 2
-9
>>> (-3) ** 2
9

幂运算符比取反运算符优先级高.

长整数

Python中可以处理大于2147483647和小于-2147483648的数,只需要在数的后面加上字母L(小写也可),如果计算中超出普通整数的范围,这个计算的结果会自动转换为长整数.

>>> 1234565431235465L * 1545151545451545 + 21
1907590684034531851190643043446L

十六进制和八进制

Python和C语言一样,使用'0x'表示十六进制,'0'表示八进制.

>>> 0xAF
175
>>> 010        
8

变量

Python中的变量不像C语言中的变量那样,需要先声明后使用,它可以在程序中直接使用,但是需要先赋值.

x = 19
print x

语句

Python 3.0以后,print变成了print().

print 34    #Python 3.0以前
print(34)    #Python 3.0以后

获取用户输入

x = input("Please input a number:")
print x

函数

pow(2, 3)        #幂函数2 ** 3
abs(-10)
round(1.0/2.0)    #四舍五入

模块

可以把模块想象成导入到Python以增强其功能的扩展.需使用命令import来导入.

>>> import math
>>> math.floor(1.2)
1.0
>>> math.ceil(1.2)
2.0

注意:需要按照"模块.函数"的格式使用这个模块的函数.

如果想转换为整数,可以使用int函数:

>>> int(math.floor(1.2))
1

在确定自己不会导入多个同名函数(从不同模块导入)的情况下,你可能不希望每次调用函数的时候,都要写上模块的名字.那么可以使用另外一种形式:

>>> from math import sqrt
>>> sqrt(9)    
3.0

提示:可以使用变量来引用函数(或Python中的大多数对象).比如通过foo=math.sqrt进行赋值,然后就可以使用foo来计算平方根了:foo(4)的结果为2.0.

cmath和复数

math中的sqrt函数只能处理浮点数,如果处理虚数,则需要用cmath(complex math, 复数)模块来处理.

>>> import cmath
>>> cmath.sqrt(-1)
1j
>>> (1+3j) * (9+4j)
(-3+31j)

可以看到,Python语言本身就提供了对复数的支持.

注意:Python中没有单独的虚数类型.它们被看作实数部分为0的复数.

回到future

通过它可以导入哪些在未来会成为标准Python组成部分的新特性.

保存并执行程序

通过命令提示符运行Python脚本

$python hello.py

让脚本像普通程序一样执行

#!/usr/bin/env python

如果按装了新版本的Python,则改成下面(具体路径会因系统而异):

#!/usr/bin/python2
or
#!/usr/bin/python3

在实际运行脚本前,必须让脚本文件具有可执行的属性:

$ chmod a+x hello.py
or
$ chmod a+x *.py

现在就可以这样运行代码了(假设路径就是当前目录):

$ hello.py

如果不起作用的话,试试:

$ ./hello.py

注释

Python使用'#'来进行注释:

#这里是注释.

字符串

单引号字符串和转义引号

在Python中使用单引号或双引号扩起来的字符为字符串,两者并没有什么不同.

"Let's go!"
'"Hello world!" she said'

或者使用转义符号'\':

'Let\'s go!'
'Let\'s come out!'

拼接字符串

使用'+'来进行字符串的拼接:

>>> x = 'hello '
>>> y = 'world!'
>>> x + y
hello world!

字符串表示,str 和 repr

str:把值转换成合理的字符串的形式
repr:会创建一个字符串,它以合法的Python表达式的形式来表示值

>>> print str(1000L)
    1000
>>> print repr("Hello, world!")
    'Hello, world!'
>>> print repr(1000L)
    1000L
>>> print 1000L
    1000
>>> print str(1000L)
    1000
>>> print str("Hello, world!")
    Hello, world!

repr(x)的功能也可以用x实现.

>>> tmp = 42
>>> print "the num is:" + tmp
Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
  TypeError: cannot concatenate 'str' and 'int' objects
>>> print "the num is:" + `tmp`
the num is:42
>>> print "the num is:" + str(tmp)
the num is:42
>>> print "the num is:" + repr(tmp)
the num is:42

注意:在Python 3.0中,已经不再使用反引号了.因此即使在旧的代码中看到了反引号,你也应该使用repr.

简而言之,str, repr和反引号是将Python值转换为字符串的3中方法.函数str让字符串更易于阅读,而repr(和反引号)则把结果字符串转换为合法的Python表达式.

事实上,str和int, long一样,是一种类型.而repr仅仅是函数.

input和raw_input的比较

>>> name = input("what is your name? ")
what is your name? Jerry
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
File "<string>", line 1, in <module>
NameError: name 'Jerry' is not defined
>>> name = input("what is your name? ")
what is your name? "Jerry"
>>> print "hello " + name
hello Jerry

input会假设用户输入的是合法的Python表达式.而raw_input会把所有的输入当作原始数据,然后将其放入字符串中:

>>> name = raw_input("what is your name? ")
what is your name? 3
>>> name = raw_input("what is your name? ")
what is your name? 3
>>> print "hello " + name
hello 3
>>> name = raw_input("what is your name? ")
what is your name? wang
>>> print "hello " + name
hello wang

除非对input有特殊的需要,否则应尽可能使用raw_input.

长字符串,原始字符串和 Unicode

如果需要写一个非常长的跨行字符串,你可以使用三个单引号或双引号代替普通引号.

>>> print '''This is a very long string.
... It continues here.
... And it's not over yet.
... ANd it's very long.
... "hello world"
... Still here.'''
This is a very long string.
It continues here.
And it's not over yet.
ANd it's very long.
"hello world"
Still here.

你可以在里面任意使用单(双)引号.

提示:普通字符串也可以跨行,需要反斜线转义.

>>> print "hello. \
... world"
hello. world
>>> 1 +2 + \
... 3 + 4
10

原始字符串不会把反斜线当作特殊字符.在原始字符串中输入的每个字符都会与书写的方式保持一致:

>>> print r'C:\nowhere'
C:\nowhere
>>> print r'C:\Program\fnord'
C:\Program\fnord

不能在原始字符串的结尾处输入反斜线.

>>> print r'C:\nowhere'
C:\nowhere
>>> print r'C:\Program\fnord'
C:\Program\fnord
>>> print r'C:\'
  File "<stdin>", line 1
      print r'C:\'
                 ^
 SyntaxError: EOL while scanning string literal
 >>> print r'C:\\'
 C:\\
 >>> print r'let's come out!'
   File "<stdin>", line 1
       print r'let's come out!'
                   ^
 SyntaxError: invalid syntax

如果要使用,则只能将反斜线单独作为一个字符串处理.

>>> print r'C:\foo\bar' + '\\'
C:\foo\bar\

在python中的普通字符串在内部是以8位的ASCII码形式存储的,而Unicode字符串则存储为16位Unicode字符,这样就能表示更多的字符集了,包括世界上大多数语言的特殊字符.

>>> u'hello'
u'hello'

可以看到,Unicode字符串使用u前缀,就像原始字符串使用r一样.

注意:在Python 3.0中,所有字符串都是Unicode字符串.

总结

函数                        描述
-----------------------------------------------------------
abs(number)                 返回数字的绝对值
cmath.sqrt(number)          返回平方根,也可应用于负数
float(object)               将字符串和数字转换为浮点数
help()                      提供交互式帮助
input(prompt)               获取用户输入
int(object)                 将字符串和数字转换为整数
long(object)                将字符串和数字转换为长整数
math.ceil(number)           返回数的上入整数,返回值的类型为浮点数
math.floor(number)          返回数的下舍整数,返回值的类型为浮点数
math.sqrt(number)           返回平方根,不是用于负数
pow(x, y[, z])              返回x的y次幂(所得结果对x取模)
raw_input(prompt)           获取用户输入,返回的类型为字符串
repr(object)                返回值的字符串表示形式
round(number[, ndigits])    根据给定的精度对数字进行四舍五入
str(object)                 将值转换为字符串