一段簡單的猜數字代碼,要求是1,要猜的數字是隨機數字1到9;2,猜數字次數為三次;3,如果猜中就打印提示語,並且結束程序;4,如果猜錯就打印正確值還有剩下的次數;5,如果次數為0,就打印結束,歡迎下次再來。
文件名為:easy_guess.py,代碼如下:
1 # !usr/bin/env python3 2 # *-* coding:utf-8 *-* 3 4 ''' 5 一個簡單的猜數字游戲 6 要猜的數字為隨機數字1到9 7 猜的次數為3 8 如果猜中就打印猜中的提示語 9 如果沒猜中就打印正確值,還有剩下的次數 10 如果次數為0,就打印結束,歡迎下次再來 11 ''' 12 13 from random import randint #導入模塊 14 15 16 #num_input = int(input("Please input a number(range 1 to 9 ) to continue: ")) #輸入數字 17 guess_time = 0 #定義猜數字次數 18 19 '''開始主循環''' 20 while guess_time < 4: 21 num_input = int(input("PLease input a number(range 1 to 9) to continue: ")) #開始輸入字符,因為從終端輸入python認為是字符串,所以要在最前面用int()函數強制轉化為整型,不然后續比較的時候會出現錯誤; 22 number = randint(1,9) #定義隨機數字,從1到9 23 remain_time = 3 - guess_time #定義剩下的猜字次數 24 25 if num_input == number: #比較輸入的數字是否和隨機數相等,代碼的第21行前如果沒有轉化成整型,這里會提示str不能與int進行比較; 26 print("Great guess, you are right!") #相等就執行 27 break #跳出主循環,后續的代碼都不會再執行 28 elif num_input > number: #比較輸入的數字是否大於隨機數 29 print("Large\n The right number is: {}\n You have {} chances!".format(number,remain_time)) #滿足條件就提示正確答案和剩余次數 30 elif num_input < number: 31 print("Small\n The right number is: {}\n You have {} chances!".format(number,remain_time)) #滿足條件就提示正確答案和剩余次數 32 33 guess_time += 1 #每次循環完成都讓猜字次數(guess_time)自加1,直到不滿足主循環條件guess_time < 4
上面的代碼並不能執行如果次數為0 就打印結束,歡迎下次再來,而且也沒有判斷用戶輸入,下面把代碼改一下,來完善一下,文件名為another_easy_guess.py:
1 # usr/bin/env python3 2 # *-* coding:utf-8 *-* 3 4 from random import randint #導入模塊 5 6 guess_time = 0 #定義猜數字次數 7 8 '''開始主循環''' 9 while guess_time < 4: 10 remain_time = 3 - guess_time #定義猜的次數 11 num_input = input("Please input a number(integer range 1 to 9) to continue(You have {} times to guess): ".format(remain_time)) #開始輸入 12 number = randint(1,9) #定義隨機數 13 14 15 if guess_time >=0 and guess_time < remain_time: #猜的次數大於0還有小於剩余次數才會執行下面的代碼塊 16 if not num_input.isdigit(): #判定輸入的是否是數字 17 print("Please input a integer to continue.") #如果不是數字,提示用戶輸入數字 18 elif int(num_input) < 0 or int(num_input) > 10: #判定是不是在我們設定的數字范圍內 19 print("Please use the number 1 to 9 to compare.") #如果不是就提示 20 elif int(num_input) == number: #判定輸入的數字是否與隨機數相等 21 print("Great guess, you are right!") 22 break 23 elif int(num_input) > number: #判定輸入數是否大於隨機數 24 print("Large\n The right number is: {}\n There are {} chances for you!".format(number,(remain_time - 1))) 25 elif int(num_input) < number: #判定輸入數是否小於隨機數 26 print("Small\n The right number is: {}\n There are {} chances for you!".format(number,(remain_time - 1))) 27 else: 28 print("You have arrived the limited, see you next time!") #次數小於剩余次數后執行 29 break #跳出循環 30 31 guess_time += 1 #猜的次數自增1直到guess_time < 4; 32 33 34 '''歷史遺留問題:1,上面的代碼只針對用戶輸入的數字,用戶輸入字符串也是會計算次數的; 35 2,如果都沒猜中且次數用完,是直接打印最后的You have arrived the limited, see you next time!而預期的提示正確答案。 36 '''
上面代碼只針對用戶輸入的是數字,如果輸入的是字符串,比如aaa,bbb也是會計算次數的。