Python--循环--for && while
for循环示例:猜数字游戏
1 winning_number = 38 2 for i in range(3): 3 guess_num = int(input("guess num:") ) 4 if guess_num == winning_number : 5 print("yes, you got it. ") 6 break 7 elif guess_num < winning_number: 8 print("think smaller...") 9 else: 10 print("think bigger!") 11 else: 12 print("you have tried too many times..")
while循环示例:死循环
1 count = 0 2 while True: 3 print("I love You!!!---%d" %(count)) 4 count += 1 5 if count > 999: 6 break
while循环示例:猜数字游戏
1 winning_number = 38 2 count = 0 3 while count <3: 4 guess_num = int(input("guess num:") ) 5 if guess_num == winning_number : 6 print("yes, you got it. ") 7 break 8 elif guess_num < winning_number: 9 print("think smaller...") 10 else: 11 print("think bigger!") 12 count +=1 13 else: 14 print("you have tried too many times..")
while循环升级:根据用户输入来决定是否终止游戏
1 winning_number = 38 2 count = 0 3 while count <3: 4 guess_num = int(input("guess num:") ) 5 if guess_num == winning_number : 6 print("yes, you got it. ") 7 break 8 elif guess_num < winning_number: 9 print("think smaller...") 10 else: 11 print("think bigger!") 12 count +=1 13 if count == 3: 14 countine_confirm = input("do you want to keep guessing..?") 15 if countine_confirm != 'n': 16 count =0