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

python osetc 198℃ 0评论

一、if语句

1
>>> 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'

二、for 语句

1
2
3
4
In [5]: words = ['cat', 'window', 'defenestrate']
In [6]: for w in words:
   ...:     print w, len(w)
   ...:

cat 3
window 6
defenestrate 12

三、 range函数

1
2
3
4
5
6
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]

四、循环语句中的break 、continue和else

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
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
1
2
3
4
5
6
7
8
9
10
11
12
13
14
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

五、pass语句

1
2
In [18]: def initlog(*args):
   ....:     pass

来源:http://linjohn.blog.51cto.com/1026193/1609673

转载请注明:osetc.com » Python2.7:流程控制语句学习

喜欢 (0)or分享 (0)
发表我的评论
取消评论

表情

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址