• 打印多个表达式,每个表达式的结果通过空格间隔
In [2]:
print "age: ", 21
age:  21

In [3]:
#打印元组时必须加上括号
In [4]:
print 1, 2, 3
1 2 3

In [5]:
print (1, 2, 3)
(1, 2, 3)

import语句

有以下四中导入形式:

  • import (module)
  • from (module) import (function)
  • from (module) import (function1), (function2), (function3), ..........
  • from (module) import *
    最后一种会导入模块内的所有函数
In [6]:
#为模块提供别名(as子语句)
import math as foobar
In [7]:
foobar.sqrt(4)
Out[7]:
2.0
In [8]:
#为函数提供别名(as子语句)
from math import sqrt as foobar
In [9]:
foobar(4)
Out[9]:
2.0

赋值语句

In [10]:
#多个变量同时赋值
x, y, z = 1, 2, 3
In [11]:
#python交换变量的值非常简单!!!
In [12]:
print x, y
1 2

In [13]:
x, y = y ,x
In [14]:
print x, y
2 1

  • 以上两个操作做的是序列解包sequence unpacking(递归解包)——讲多个值的序列解开,然后放个变量序列中
In [15]:
#这个特性允许函数或者方法返回多个值
#此时等号左右两边的量的数要相等,而且对应正确
In [16]:
pbook = {'Zk': '510', 'Zps' : '877'}
In [19]:
key, value = pbook.popitem()
In [20]:
print key , value
Zps 877

  • 链式赋值(chained assignment)
In [21]:
x = y = 3
In [22]:
print x, y
3 3

  • 增量赋值(augmented assignment),这个功能C也有
In [23]:
s = "Hello,"
In [24]:
s += "world!"
In [25]:
s *= 2
In [26]:
s
Out[26]:
'Hello,world!Hello,world!'
In []: