python while條件和if判斷的總練習

輸出123456 89的數字算法

num =1
while num < 11:
    if num == 7:
        pass
    else:
        print(num)
    num = num + 1

 

輸出1-100的奇數與偶數測試

奇數方法

   num = 0
   while num < 101:
     answer = num % 2
     if answer == 0:
       pass
     else:
       print(num)
   num = num + 1spa

 

偶數方法
   num = 0 
   while num < 101:
     answer = num % 2
     if answer == 0:
       print(num)
     else:
       pass
   num = num + 1

 

1到10相加code

n = 1
s = 0
while n < 11:
    n = n + 1
    s = s + n
    print(s)

算法思路:
s = 0
n = 1
n = n + 1
s =(n + 1 + s) *10次
2  1 + 1 + 0  1
5  2 + 1 + 2  2
9  3 + 1 + 5  3
...
65        10

 

 

1-2+3-4+5-6..10全部數的和blog

'1-2+3-4+5-6+7..10'
n = 1 #n就是1-10的數列
s = 0 #s以前數的總和
while n < 11:
    answer = n % 2 #判斷數列是偶數仍是奇數
    if answer == 0:
        s = s - n #數列遇到偶數時相減
    else:
        s = s + n #數列遇到奇數時相加
    n = n + 1 #產生1-10的數列
    print(s) #打印語句塊執行過程的和
print(s) #打印總和

算法思路:
s = 0
n = 1
奇數      偶數
s = s + n   s = s - n
 
 
 

 

break 跳出循環input

num = 0
while num < 11:
        if num == 7:
                print("hi")
                break
        else:
                print(num)
                num = num + 1
print("---and---")

輸出:
1
2
...
6
hi
---and---

當num等於7的時候打印的是hi
break跳出循環語句塊

 

 continue 繼續循環
num = 0
while num < 11:
        if num == 7:
                print("hi")
                continue
        else:
                print(num)
                num = num + 1
print("---and---")

輸出:
1
2
...
6
hi
hi
...

當num等於7的時候continue 繼續從等於7開始循環
結果打印1到6後面是無限個hi

 

 用戶登陸測試,3次錯誤提醒
'登錄3次錯誤提醒'
num = 0
while num < 3:
        user = input("請輸入帳號:")
        passwd = int(input("請輸入密碼:"))
        if user == "root" and passwd == 123456:
                print("登錄成功")
                break
        else:
                print("帳戶或密碼錯誤")
                num = num + 1
相關文章
相關標籤/搜索