流程控制

2017-03-01  本文已影响31人  交易狗二哈

流程控制

if elif else break continue

普通条件语句

s = input('birth: ')
birth = int(s)
if birth < 1990:
    print('90前')
elif birth < 2000:
    print('90后')
else :
    print('00后')
print('-----------------------------------------------------------------')

三元运算

name = 'xiaoming' if 1 == 1 else 'xiaohong'

for in

names = ['Michael', 'Bob', 'Tracy']             #迭代list...里的元素
for name in names:
    print(name)

sum = 0
for x in [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]:
    sum = sum + x
print(sum)

sum = 0
for x in range(101):
    sum = sum + x
print(sum)

while

>>> t = 0
>>> while t < 3:
              print(t)
              t += 1
0
1
2

break

n = 1
while n <= 100:
    if n > 10: # 当n = 11时,条件满足,执行break语句
        break # break语句会结束当前循环
    print(n)
    n = n + 1
print('END')

continue

n = 0                                          
while n < 10:
    n = n + 1
    if n % 2 == 0: # 如果n是偶数,执行continue语句
        continue # continue语句会直接继续下一轮循环,后续的print()语句不会执行
    print(n)

enumrate

>>> li = [11,22,33]
>>> for k,v in enumerate(li, 1):
             print(k, v)
1 11
2 22
3 33
上一篇 下一篇

猜你喜欢

热点阅读