Skip to content Skip to main navigation Skip to footer

Python2.7:流程控制语句学习

一、if语句

>>> x = int(raw_input(“Please enter an integer: “))Please enter an integer: 42>>> if x < 0:... x = 0... print 'Negative changed to zero'... elif x == 0:... print 'Zero'... elif x == 1:... print 'Single'... else:... print 'More' [/code] 二、for 语句 [code] In [5]: words = ['cat', 'window', 'defenestrate'] In [6]: for w in words: ...: print w, len(w) ...: [/code] cat 3 window 6 defenestrate 12 三、 range函数 [code] In [8]: range(5, 10) Out[8]: [5, 6, 7, 8, 9] In [9]: range(0, 10, 3) Out[9]: [0, 3, 6, 9] In [10]: range(-10, -100, -30) Out[10]: [-10, -40, -70] [/code] 四、循环语句中的break 、continue和else [code] In [14]: for n in range(2,10): for x in range(2,n): if n%x==0: print n,'equals',x,'*',n/x break else: print n,'is a prime number' ....: 2 is a prime number 3 is a prime number 4 equals 2 * 2 5 is a prime number 6 equals 2 * 3 7 is a prime number 8 equals 2 * 4 9 equals 3 * 3 [/code] [code] In [16]: for num in range(2, 10): ....: if num % 2 == 0: ....: print "Found an even number", num ....: continue ....: print "Found a number", num ....: Found an even number 2 Found a number 3 Found an even number 4 Found a number 5 Found an even number 6 Found a number 7 Found an even number 8 Found a number 9 [/code] 五、pass语句 [code] In [18]: def initlog(*args): ....: pass [/code] 来源:http://linjohn.blog.51cto.com/1026193/1609673

0 Comments

There are no comments yet

Leave a comment

Your email address will not be published.