1、原始游戲 (input 內建函數用於接收用戶輸入)
temp = input("please input an integer:") guess = int(temp) if guess == 8: print("you are right!") print("no gift evec though you guess right!") else: print("wrong!") print("right number is 8!") print("gave ove!")
2、改進小游戲
給出輸入偏離8時的提示:
不限制用戶執行程序的次數,直到猜中。
temp = input("please input the number:") guess = int(temp) while guess != 8: print("wrong!") if guess > 8: print("big!") else: print("small!") temp = input("try again:") guess = int(temp) print("you are right!") print("game over!")
3、改進小游戲
引入隨機答案。
temp = input("please input an number:") guess = int(temp) import random secret = random.randint(1,10) while guess != secret: print("wrong!") if guess > secret: print("big!") else: print("small!") temp = input("try again:") guess = int(temp) print("you are right!") print("game over!")
4、改進小游戲
只給三次機會。
方法1:
temp = input("please input an number:") guess = int(temp) import random secret = random.randint(1,10) times = 0
while times < 3: if guess == secret: print("you are right!") break
else: print("you are wrong!") if guess != secret: if guess > secret: print("big") else: print("small") times += 1
if times < 3: temp = input("try again:") guess = int(temp) if times == 3: print("times over!")
方法2:
temp = input("please input an number:") guess = int(temp) import random secret = random.randint(1,10) times = 1
while guess != secret and times < 3: if guess > secret: print("big") else: print("small") temp = input("please try again:") guess = int(temp) times += 1
if times == 3 and guess != secret: print("time out!,game over") else: print("right")