print ‘Age‘,42 print 1,2,3
>>> name = ‘Gumby‘ >>> salutation = ‘Mr.‘ >>> greeting = ‘Hello‘ >>> print greeting,salutation,name Hello Mr. Gumby >>> print greeting + ‘,‘,salutation,name Hello, Mr. Gumby >>> print greeting,‘,‘,salutation,name Hello , Mr. Gumby
import somemodule from somemodule import somefunction from somemodule import somefunction1 somefunction2 somefunction3 from somemodule import *
>>> import math as foobar >>> print foobar.sqrt(9) 3.0
>>> from math import sqrt as foobar >>> foobar(4) 2.0
>>> x,y,z = 1,2,3 >>> print x,y,z 1 2 3
>>> y=x >>> print x,y,z 1 1 3 >>> x,z=z,x >>> print x,y,z 3 1 1
>>> dd = {‘name‘:‘Anti‘,‘Age‘:42} >>> key,value = dd.popitem() >>> key ‘Age‘ >>> value 42
x = y = somefunction() # y = somefunction() x = y
x = somefunction()
y = somefunction()
>>> x = 2 >>> x += 1 #加等 >>> x 3 >>> x *= 6 #乘等 >>> x 18 >>> x -= 2 #减等 >>> x 16
>>> bool(‘I think, therefor I am.‘) True >>> bool([]) False >>> bool({‘name‘:‘Aoto‘}) True >>> bool(0) False
name = raw_input("What‘s your name ? ") if name.endswith(‘Gumby‘): print ‘Hello, Mr.Gumby.‘ else: print ‘Hello, stranger.‘ #输出如下 What‘s your name ? Gumby Hello, Mr.Gumby.
if ...: do ... elif ...: do ... else: do ...
>>> x = y = [1,2,3] >>> z = [1,2,3] >>> x == y True >>> x == z True >>> x is y True >>> x is z False #注意
number = input(‘Enter a number between 1 and 10 : ‘) if number <= 10 and number > 1: print ‘Great!‘ else: print ‘Wrong!‘ #输出如下 Enter a number between 1 and 10 : 8 Great!
name = raw_input(‘Please input your name: ‘) or ‘<Unknow>‘ print name #输出如下: Please input your name: <Unknow> #输出如下: Please input your name: Aoto Aoto
a if b else c
x=2 if 10>=2 else 4 print x result = ‘gt‘ if 1 >3 else ‘lt‘ print result
if not condition: crash program
>>> age = 10 >>> assert 0 < age < 100 >>> age = -1 >>> assert 0 < age < 100 Traceback (most recent call last): File "<stdin>", line 1, in <module> AssertionError
>>> age = -1 >>> assert 0 < age < 100, ‘The age must be reallistic.‘ Traceback (most recent call last): File "<stdin>", line 1, in <module> AssertionError: The age must be reallistic.
name = ‘‘ while not name or name.isspace(): name = raw_input(‘Please enter your name: ‘) print ‘Hello,%s!‘ % name #输出如下: Please enter your name: Please enter your name: #输入空格是无效的,要求重新输入 Please enter your name: dodo Hello,dodo!
kl = [] for i in range(1,10,2): kl.append(i) print kl #输出如下 [1, 3, 5, 7, 9]
>>> d = {‘name‘:‘ToTo‘,‘Age‘:23,‘Address‘:‘BeiJing‘} >>> for key in d: ... print key,‘corresponds to‘,d[key] ... Age corresponds to 23 name corresponds to ToTo Address corresponds to BeiJing >>> for k,v in d.items(): ... print k,‘corresponds to‘,v ... Age corresponds to 23 name corresponds to ToTo Address corresponds to BeiJing
names = [‘Anne‘,‘Beth‘,‘George‘,‘Damon‘] ages = [12,23,78,67] for name,age in zip(names,ages): print name,‘is‘,age,‘years old.‘ #输出如下 Anne is 12 years old. Beth is 23 years old. George is 78 years old. Damon is 67 years old.
name = [‘Anne‘,‘Beth‘,‘George‘,‘Damon‘] age = [12,23,78,67] for i in range(len(name)): print name[i],‘is‘,age[i],‘years old.‘ #输出如下 Anne is 12 years old. Beth is 23 years old. George is 78 years old. Damon is 67 years old.
zip(range(5),xrange(1000))
输出:[(0, 0), (1, 1), (2, 2), (3, 3), (4, 4)]
for string in strings: if ‘xxx‘ in string: index = strings.index(string) strings[index] = ‘[censored]‘
index = 0 for string in strings: if ‘xxx‘ in string: strings[index] = ‘[censored]‘ index += 1
for index,string in enumerate(strings): if ‘xxx‘ in string: string[index] = ‘[censored]‘
>>> sorted([4,3,5,2,3,6,9,0]) [0, 2, 3, 3, 4, 5, 6, 9] >>> sorted(‘Hello,world!‘) [‘!‘, ‘,‘, ‘H‘, ‘d‘, ‘e‘, ‘l‘, ‘l‘, ‘l‘, ‘o‘, ‘o‘, ‘r‘, ‘w‘] >>> list(reversed(‘Hello,world!‘)) [‘!‘, ‘d‘, ‘l‘, ‘r‘, ‘o‘, ‘w‘, ‘,‘, ‘o‘, ‘l‘, ‘l‘, ‘e‘, ‘H‘] >>> ‘‘.join(reversed(‘Hello,world!‘)) ‘!dlrow,olleH‘
from math import sqrt for n in range(99,0,-1): root = sqrt(n) if root == int(root): print root,n break #结果如下,求出0-100范围内最大的平方数 9.0 81
for x in seq: if condition1:continue if condition2:continue if condition3:continue do_something() do_something_else() do_another_thing() etc()
for x in seq: if not(condition1 or condition1 or condition1): do_something() do_something_else() do_another_thing() etc()
while True: word = raw_input(‘Please enter a word: ‘) if not word: break #处理word print ‘The word was ‘ + word
from math import sqrt for n in range(99,0,-1): root = sqrt(n) if root == int(root): print root,n break else: print "Don‘t find it."
>>> [x*x for x in range(5)] [0, 1, 4, 9, 16] >>> [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) if y<=x] [(0, 0), (1, 0), (1, 1), (2, 0), (2, 1), (2, 2)] >>> [(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‘,‘arnord‘,‘bob‘] print [boy + ‘ + ‘ + girl for boy in boys for girl in girls if boy[0]==girl[0]] #结果如下 [‘chris + clarice‘, ‘arnord + alice‘, ‘bob + bernice‘]
girls = [‘alice‘,‘bernice‘,‘clarice‘,‘bibl‘] boys = [‘chris‘,‘arnord‘,‘bob‘] letterGirls = {} for girl in girls: letterGirls.setdefault(girl[0],[]).append(girl) print letterGirls print [Boy + ‘ + ‘ + Girl for Boy in boys for Girl in letterGirls[Boy[0]]] #结果如下 {‘a‘: [‘alice‘], ‘c‘: [‘clarice‘], ‘b‘: [‘bernice‘, ‘bibl‘]} [‘chris + clarice‘, ‘arnord + alice‘, ‘bob + bernice‘, ‘bob + bibl‘]
if name == ‘Raplh Auldus Melish‘: print "Welcome!" elif name == ‘Enid‘: #在elif这个代码块中,必须要有一个执行语句,否则空代码块在Python中是非法的,解决方法就是加一个pass #还没完 pass elif name == ‘Bill Gates‘: print "Access Denied!"
>>> x = 1 >>> del x >>> x Traceback (most recent call last): File "<stdin>", line 1, in <module> NameError: name ‘x‘ is not defined
>>> x = ["Hello",‘World‘] >>> y = x >>> y[1] = "python" >>> x [‘Hello‘, ‘python‘]
>>> del x >>> x Traceback (most recent call last): File "<stdin>", line 1, in <module> NameError: name ‘x‘ is not defined >>> y [‘Hello‘, ‘python‘]
>>> exec "print ‘Hello,world!‘" Hello,world!
>>> from math import sqrt >>> exec "sqrt = 1" >>> sqrt(4) Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: ‘int‘ object is not callable
>>> from math import sqrt >>> scope = {} >>> exec ‘sqrt = 1‘ in scope >>> sqrt(4) 2.0 >>> scope[‘sqrt‘] 1
原文:http://www.cnblogs.com/zhangpf/p/7593956.html