python控制结构实训_《python 从入门到精通》§5 控制结构
§5控制結構
2009-8-17
磁針石:xurongzhong#gmail.com
§5.1關于print和import更多的東東
打印多個值:
>>>
print 'Age:', 42
Age: 42
輸出時會有空格分隔。為了避免空格,可以使用“+".
在腳本中,這樣就不會換行:
'Hello,',
print 'world!'
輸出Hello,
world!.
import的格式:
import
somemodule
from
somemodule import somefunction
from
somemodule import somefunction, anotherfunction, yetanotherfunction
from
somemodule import *
import
math as foobar
§5.2賦值技巧
>>> x, y, z = 1, 2, 3
>>> print x, y, z
1 2 3
>>> x, y = y, x
>>> print x, y, z
2 1 3
>>> values = 1, 2, 3
>>> values
(1, 2, 3)
>>> x, y, z = values
>>> x
1
注意這種情況要求左右的值個數相同。Python 3.0中可以:a, b, rest* = [1, 2, 3, 4]。
x
= y = somefunction()
§5.3塊
:表示縮進
§5.4條件判斷
代表False的有:False None
0 "" () [] {},其他都為True.
>>>
bool('I think, therefore I am')
True
python會自動進行這種類型轉換。
name
= raw_input('What is your name? ')
if
name.endswith('Gumby'):
if
name.startswith('Mr.'):
'Hello, Mr. Gumby'
elif
name.startswith('Mrs.'):
'Hello, Mrs. Gumby'
else:
'Hello, Gumby'
else:
'Hello, stranger'
比較操作:
x
== y x equals y.
x < y x is less than y.
x > y x is greater than y.
x >= y x is greater than or equal to y.
x <= y x is less than or equal to y.
x != y x is not equal to y.
x is y x and y are the same object.
x is not y x and y are different objects.
x in y x is a member of the container
(e.g., sequence) y.
x not in y x is not a member of the
container (e.g., sequence) y.
COMPARING INCOMPATIBLE
比較也可以嵌套:0 < age < 100
>>>
x = y = [1, 2, 3]
>>> z = [1, 2, 3]
>>> x == y
True
>>> x == z
True
>>> x is y
True
>>> x is z
False
不要在基本的,不可改變的類型,比如numbers and strings中使用is,這些類型在python內部處理。
三元運算:a if b else c
斷言:
>>>
age = -1
>>> assert 0 < age < 100,
'The age must be realistic'
Traceback (most recent call last):
File "", line 1, in
?
AssertionError: The age must be realistic
§5.5循環
name = ''
while not name:
name = raw_input('Please enter your name:
')
print 'Hello, %s!' % name
for number in range(1,101):
print number
xrange一次只產生一個數,在大量循環的時候可以提高效率,一般情況沒有明顯效果。
與字典配合使用:
d
= {'x': 1, 'y': 2, 'z': 3}
for key in d:
print key, 'corresponds to', d[key]
不過排序的為您提要自己處理。
names
= ['anne', 'beth', 'george', 'damon']
ages = [12, 45, 32, 102]
for i in range(len(names)):
print names[i], 'is', ages[i], 'years old'
>>>
zip(names, ages)
[('anne', 12), ('beth', 45), ('george',
32), ('damon', 102)]
for name, age in zip(names, ages):
print name, 'is', age, 'years old'
>>> zip(range(5),
xrange(100000000))
[(0, 0), (1, 1), (2, 2), (3, 3), (4, 4)]
for index, string in enumerate(strings):
if 'xxx' in string:
strings[index] = '[censored]'
from math import sqrt
for n in range(99, 0, -1):
root = sqrt(n)
if root == int(root):
print n
break
from math import sqrt
for n in range(99, 81, -1):
root = sqrt(n)
if root == int(root):
print n
break
else:
print "Didn't find it!"
可見for語句也可以有else。
§5.6List Comprehension
[x*x for x in range(10) if x % 3 == 0]
[0, 9, 36, 81]
>>> [(x, y) for x in range(3) for
y in range(3)]
[(0, 0), (0, 1), (0, 2), (1, 0), (1, 1),
(1, 2), (2, 0), (2, 1), (2, 2)]
>>> girls = ['alice', 'bernice',
'clarice']
>>> boys = ['chris', 'arnold',
'bob']
>>> [b+'+'+g for b in boys for g
in girls if b[0] == g[0]]
['chris+clarice', 'arnold+alice', 'bob+bernice']
這里類似數據庫里面的連接。一種更有效的方法:
girls
= ['alice', 'bernice', 'clarice']
boys = ['chris', 'arnold', 'bob']
letterGirls = {}
for girl in girls:
letterGirls.setdefault(girl[0],
[]).append(girl)
print [b+'+'+g for b in boys for g in
letterGirls[b[0]]]
§5.7pass, del,和exec
pass:什么都不做
del:刪除變量
>>> from math import sqrt
>>> scope = {}
>>> exec 'sqrt = 1' in scope
>>> sqrt(4)
2.0
>>> scope['sqrt']
1
>>> len(scope)
2
>>> scope.keys()
['sqrt', '__builtins__']
eval是內置的,和exec類似。exec針對陳述,eval針對表達式。Python 3.0中,raw_input被命名為input.此處尚未完全理解。
總結
以上是生活随笔為你收集整理的python控制结构实训_《python 从入门到精通》§5 控制结构的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: case when 子查询_Oracle
- 下一篇: 早知道伤心总是难免的是哪首歌啊?