1. 程式人生 > 實用技巧 >流程控制之while(2)

流程控制之while(2)

1. 使用while迴圈輸出1 2 3 4 5 6     8 10
count = 0
while count < 10:
count += 1
if count == 7 or count == 9:
continue
print(count)
2.求1-100的所有數的和
num = 0
count = 1
while count <= 100:
num = num+ count #num+=count
count += 1
print(num)
3. 輸出 1-100 內的所有奇數
count = 0
while count <100:
count+=1
if count%2==1:
print(count)
4. 輸出 1-100 內的所有偶數
count = 0
while count <100:
count+=1
if count%2==0:
print(count)
5. 求1-2+3-4+5 ... 99的所有數的和
num = 0
count = 1
while count <= 100:
if count%2==0:
num = num-count #num-=count
elif count%2==1:
num = num+ count #num+=count
count += 1
print(num)
6.使用者登陸(三次機會重試)
name = "sean"
pwd ="11"
count = 0
while count <3:
inp_name = input('your name:')
inp_pwd =input('your pwd:')
if inp_name == name and inp_pwd == pwd:
print('success')
break
else:
print('try again')
count +=1
else:
print('賬號已鎖定,請30分鐘後再次嘗試')
7:猜年齡遊戲:允許使用者最多嘗試3次,3次都沒猜對的話,就直接退出,如果猜對了,列印恭喜資訊並退出
age_of_sean='18'
count=0
while count < 3:
age = input('age_of_sean is:')
if age == age_of_sean:
print("It's good")
break
else:
print('Try again')
count+=1
else:
print('本輪遊戲結束,下次加油!')
8:猜年齡遊戲升級版
要求:
允許使用者最多嘗試3次
每嘗試3次後,如果還沒猜對,就問使用者是否還想繼續玩,如果回答Y或y, 就繼續讓其猜3次,以此往復,如果回答N或n,就退出程式
如何猜對了,就直接退出
age_of_sean='18'
count=0
while True:
if count == 3:
choice=input('如果繼續,請輸入Y或y,否則輸入N或n退出: ')
if choice == 'Y' or choice == 'y': #區分大小寫
count=0
else:
print('遊戲結束,下次繼續加油哦')
break
age=input('age_of_sean is: ')
if age == age_of_sean:
print("It's good")
break
count+=1