1. 程式人生 > >009:了不起的分支和循環3

009:了不起的分支和循環3

for循環 個數 三種 可選 fis sta 密碼 love bre

筆記

1.range()

語法:range([start],stop[,step=1]),有三個參數,中括號中的內容可選,step是步進,這個BIF的作用是生成一個從start參數的值開始到stop參數的值結束的數字序列,經常與for循環聯合使用。

for i in range(0, 10, 2):
    print(‘I Love FishC‘)

會打印出五次I Love FishC

2.break,跳出循環體

3.continue,終止本輪 循環,並開始下一輪循環(如果下一輪循環的條件為真)

測試題

1.請問 range(10) 生成哪些數?

答:0,1,2,3,4,5,6,7,8,9

2.讀懂

while True:
    while True:
        break
        print(1)
    print(2)
    break
print(3)

3.設計一個驗證用戶密碼程序,用戶只有三次機會輸入錯誤,不過如果用戶輸入的內容中包含"*"則不計算在內。

count = 3
password = "156465"
temp = input("請輸入密碼:")
while count:
    if temp == password:
        print("密碼正確!Loading...")
        break
    elif ‘*‘ in temp:
        temp = input("密碼錯誤,不能帶有‘*’,你還有 %d 次機會,請重新輸入:"%count)
    else:
        count -= 1
        temp = input("密碼錯誤,你還有 %d 次機會,請重新輸入:"%count)
        if count == 1:
            print("密碼錯誤,遊戲結束")
            break

4.編寫一個程序,求 100~999 之間的所有水仙花數。
如果一個 3 位數等於其各位數字的立方和,則稱這個數為水仙花數。例如:153 = 1^3 + 5^3 + 3^3,因此 153 就是一個水仙花數。

for i in range(100,1000):
    temp = i
    temp = (temp//100)**3 + ((temp//10)%10)**3 + (temp%10)**3
    if temp == i:
        print(i,end=‘ ‘)

5.三色球問題
有紅、黃、藍三種顏色的球,其中紅球 3 個,黃球 3 個,藍球 6 個。先將這 12 個球混合放在一個盒子中,從中任意摸出 8 個球,編程計算摸出球的各種顏色搭配。

print(‘red\tyellow\tblue‘)
for red in range(0, 4):
    for yellow in range(0, 4):
        for blue in range(2, 7):
            if red + yellow + blue == 8:
                print(red, ‘\t‘, yellow, ‘\t‘, blue)    
                

註釋:range(2,7)是產生[2, 3, 4, 5, 6]5個數,綠球不能是1個,因為如果綠球是1個的話,紅球 + 黃球需要有7個才能符合題意,而紅球和黃球每種只有3個,因此是range(2, 7)

009:了不起的分支和循環3