我從一本書中發明了這個猜測遊戲的想法,Invent With Python。我不喜歡原始腳本沒有涵蓋重新猜測數字或錯誤地使用不在1-20中的數字的可能性,所以我修改了它。該程序很好用,但是,如果/ elif/else代碼塊只是我的頭部。如果聲明,避免嵌套? (Python 2.7)
我想重寫腳本,而不必嵌套,如果在if中。我甚至不知道如何做到這一點。任何人都可以請幫助我 - 只有一個例子說明這個程序如何在沒有嵌套的情況下工作會很棒!
下面是完整的小腳本:
from random import randint
from sys import exit
name = raw_input("Hello! What's your name? ")
print "Well %s, I'm thinking of a number between 1 and 20." % name
print "Since I'm a benevolent computer program, I'll give you 6 guesses."
secret_number = randint(1, 20)
guesses_left = 6
already_guessed = []
while guesses_left > 0:
try:
guess = int(raw_input("Take a guess: "))
if guess >= 1 and guess <= 20 and guess not in already_guessed:
already_guessed.append(guess)
guesses_left -= 1
if guess == secret_number:
print "You win! %d was my secret number!" % secret_number
exit(0)
elif guess < secret_number:
print "Your guess is too low!"
elif guess > secret_number:
print "Your guess is too high!"
elif guess in already_guessed:
print "You already guessed that!"
else:
print "Not a number between 1 - 20!"
print "Please try again!"
print "You have %d guesses left!" % guesses_left
except ValueError:
print "Invalid input! Please try again!"
您可以使用[的'繼續'語句](https://docs.python.org/3/tutorial/controlflow.html#break-and-continue-statements-and-else-clauses-on-loops),這也將有助於除了輸入從'try'。 – Ryan