我是使用2.7.11的Python初學者,我做了一個猜謎遊戲。這是到目前爲止我的代碼Python猜測遊戲
def game():
import random
random_number = random.randint(1,100)
tries = 0
low = 0
high = 100
while tries < 8:
if(tries == 0):
guess = input("Guess a random number between {} and {}.".format(low, high))
tries += 1
try:
guess_num = int(guess)
except:
print("That's not a whole number!")
break
if guess_num < low or guess_num > high:
print("That number is not between {} and {}.".format(low, high))
break
elif guess_num == random_number:
print("Congratulations! You are correct!")
print("It took you {} tries.".format(tries))
playAagain = raw_input ("Excellent! You guessed the number! Would you like to play again (y or n)? ")
if playAagain == "y" or "Y":
game()
elif guess_num > random_number:
print("Sorry that number is too high.")
high = guess_num
guess = input("Guess a number between {} and {} .".format(low, high))
elif guess_num < random_number:
print("Sorry that number is too low.")
low = guess_num
guess = input("Guess a number between {} and {} .".format(low, high))
else:
print("Sorry, but my number was {}".format(random_number))
print("You are out of tries. Better luck next time.")
game()
- 我將如何整合的系統,使得它如此每當用戶猜測正確的號碼,它包括反饋給儘可能少的花費要正確預測的數量的猜測。像有多少猜測高分花了他們,並改變它,只有當它被打
你可能想改變'如果playAagain ==「Y」或「Y」:''到如果playAagain.lower()==「y」:'或'如果playAagain ==「y」或playAgain ==「Y」:' –
只是一些建議和與您的問題無關的問題。 1)。你應該使用一致的縮進,(通常約定是每層4個空格)。 2)。不要在你的函數中導入模塊,在腳本的頂部執行它。 3)。爲什麼你打破了糟糕的輸入循環? 4)。不要通過在自己內部調用'game()'來重新啓動遊戲,請使用循環。 5)。通過重構你的代碼,你可以擺脫其中的2個'guess = input(...')行。 –