1. 程式人生 > >三、python中的三種機制

三、python中的三種機制

順序

和大多數變成語言一樣(此處略)

選擇

if…else…
if…elif…elif…else…
注意:後面的冒號和其他程式語言的不同點

例子1:剪刀石頭布遊戲

import random

player = int(input("請輸入數字——0(剪刀)1(石頭)2(布):"))
computer = random.randint(0,2)

if (player == 0 and computer == 2) or (player == 1 and computer == 0) or (palyer == 2 and computer == 1):
    print("player win!"
) elif player == computer: print("draw") else: print("computer win!")

例子2:坐火車過安檢

# if巢狀(執行事情有先後順序)
is_ticket = 1
is_knife = 1

if is_ticket == 1:
    print("請進行安檢!")
    if is_knife == 1:
        print("您隨身攜帶違禁物品,請等待處理!")
    else:
        print("安檢通過,請乘車!")
else:
    print("您還未購票,請買票之後再進站!"
)

迴圈

兩種:while和for
break和continue

例子1:列印1-100之間的數

i = 1
while i < = 100:
    print(i)
    i+=1

例子2:列印圖形

*
**
***
****
******
i= 1
while i <= 5:
    j = 1
    while j <= i:
        print("*",end=" ")
        j+=1
    print(" ")
    i += 1
迴圈問題的框架
i = 1
while i <= 100:
    程式碼
    i
+= 1

例子3:列印九九乘法表

i = 1
while i <= 9:
    j = 1
    while j <= i:
        print("%d*%d=%d\t"%(j,i,i*j),end="") #不換行顯示
        j += 1
    print(" ") #換行
    i += 1

例子4:列印1-100之間的前20個偶數

i = 1
k = 0
while i < 100:
    if i % 2 == 0:  
        if k == 20:
            break
        print(i)
        k += 1
    i += 1

例子5:for迴圈
迴圈輸出字串的內容

name = 'zhangsan'
for temp in name:
    print(temp)

例子7:使用break來結束迴圈

i = 1
while i < 5:
    if i = 3:
        break  #break用來結束while迴圈
    print(i)
    i += 1

例子8:使用continue來結束本次迴圈

i = 1
while i < 5:
    if i = 3:
        continue  #continue用來結束本次迴圈,執行下一次迴圈
    print(i)
    i += 1