python控制流教程_python 教程 第四章、 控制流

第四章、 控制流

控制语句后面要加冒号:

1)    if语句

if guess == number:

print 'Congratulations, you guessed it.' # New block starts here

elif guess < number:

print 'No, it is a little higher than that' # Another block

else:

print 'No, it is a little lower than that'

if not False and True: #组合条件

print "OK"

注:Python暂时没有switch语句

2)    while语句

注:while语句有一个可选的else从句

while running:

guess = int(raw_input('Enter an integer : '))

if guess == number:

print 'Congratulations, you guessed it.'

running = False # this causes the while loop to stop

elif guess < number:

print 'No, it is a little higher than that'

else:

print 'No, it is a little lower than that'

else:

print 'The while loop is over.'

3)    range语句

print range(10) #[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

print range(5,10) #[5, 6, 7, 8, 9]

print range(1,10,3) #[1, 4, 7]

print range(-10, -100, -30) #[-10, -40, -70]

用法参考help(range)

4)    for循环

a = ['apple', 'banana', 'carrot']

for i in range(len(a)): #range()和len()一起用于字符串索引

print a[i]

#apple

#banana

#carrot

带逗号的print语句输出的元素之间会自动添加空格

for i in range(len(a)):

print a[i], #带,的print语句

# apple banana carrot

C/C++中的for (int i = 0; i < 5; i++),等价于Python:for i in range(0,5)。

5)    break语句

while True:

s = raw_input('Enter something : ')

if s == 'quit':

break

print 'Length of the string is', len(s)

print 'Done'

6)    continue语句

while True:

s = raw_input('Enter something : ')

if s == 'quit':

break

if len(s) < 3:

continue

print 'Input is of sufficient length'

7)    条件表达式

x, y = 3, 4

small = x if x < y else y

print small #3

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值