流程控制主要分爲三大類:spa
一、if 判斷語句code
二、while 循壞語句blog
三、for 循壞語句input
下面以舉例說明:class
if 判斷語句:循環
user1 = 'seven' user2 = 'alex' password1 = 123 count = 0 while True: if count >= 3: print('end') break user = input('用戶名:') password = int(input('密碼:')) if (user == user1 or user == user2) and password == password1: print('登入成功') break else: print('登入失敗') count += 1 print('錯誤次數', count)
while 循環語句:密碼
password = '234' count = 0 tag = 1 while tag: if count == 3: print('帳戶鎖定') break user = input('請輸入用戶名:') password1 = input('請輸入密碼:') if user == username and password1 == password: while tag: a = input('>>:') if a == '退出': tag = 0 else: print(f'執行{a}命令') else: print('輸入錯誤') count += 1
for 循序語句:word
# 9*9乘法口訣 for i in range(1, 10): for j in range(1, i + 1): print(f'{i}*{j}={i * j}', end='\t') print()
結果:tab
1*1=1
2*1=2 2*2=4
3*1=3 3*2=6 3*3=9
4*1=4 4*2=8 4*3=12 4*4=16
5*1=5 5*2=10 5*3=15 5*4=20 5*5=25
6*1=6 6*2=12 6*3=18 6*4=24 6*5=30 6*6=36
7*1=7 7*2=14 7*3=21 7*4=28 7*5=35 7*6=42 7*7=49
8*1=8 8*2=16 8*3=24 8*4=32 8*5=40 8*6=48 8*7=56 8*8=64
9*1=9 9*2=18 9*3=27 9*4=36 9*5=45 9*6=54 9*7=63 9*8=72 9*9=81 di
練習題:
# 求1-100的全部數的和 sum1 = 0 for i in range(101): sum1 += i print(sum1)
結果:5050
#使用 while循環輸出1234568910 count = 0 l1 = range(0, 11) len(range(0, 11)) while count < len(range(1, 11)): count += 1 if count == 7: continue else: print(l1[count])
結果:
1
2
3
4
5
6
8
9
10
# 輸出1-100的全部奇數 # for i in range(1,100,2): # print(i) count = 1 while count <= 100: if count % 2 != 0: print(count) count += 1
結果:
1
3
5
7
9
11
13
15
17
19
21
23
25
27
29
31
33
35
37
39
41
43
45
47
49
51
53
55
57
59
61
63
65
67
69
71
73
75
77
79
81
83
85
87
89
91
93
95
97
99
# 求1-2+3-4+5-.....99的全部數之和 sum1 = 0 sum2 = 0 sum3 = 0 for i1 in range(1, 100, 2): sum1 += i1 print(sum1) for i2 in range(2, 100, 2): sum2 += i2 print(sum2) sum3 = sum1 - sum2 print(sum3)
結果:
2500
2450
50
# 猜年齡 age = 18 tab = True count = 1 while tab: age1 = input('請您猜想個人年齡:') age1 = int(age1) if age1 == age: print('恭喜您猜對了') tab = False break elif count >= 3: a = input('猜錯啦,請問是否要繼續猜想年齡呢:') if a == 'y' or a == 'Y': count = 1 continue
# * # *** # ***** # ******* # ********* a = int(input('行數:')) for i in range(1, a+1): print(' '*(a - i), end='') print('*'*(2 * i - 1))
結果:
* *** ***** ******* *********