我昨晚才开始学习Python,我试图编写一个简单的猜谜游戏,并提供更改猜词的选项。我想知道如何简化它。
guess_word = "Giraffe"
guess = ""
guess_count = 0
guess_limit = 4
out_of_guesses = False
Question = input("Do you want to change guess word?")
if Question == "Yes":
guess_word = input("Please input new word:")
while guess != guess_word and not out_of_guesses:
if guess_count < guess_limit:
guess = input("Please make a guess: ")
guess_count = guess_count + 1
else:
out_of_guesses = True
if out_of_guesses:
print("Out of Guesses, You Lose")
else:
print("You win, the word was " + guess_word + "!")
else:
while guess != guess_word and not out_of_guesses:
if guess_count < guess_limit:
guess = input("Please make a guess: ")
guess_count = guess_count + 1
else:
out_of_guesses = True
if out_of_guesses:
print("Out of Guesses, You Lose")
else:
print("You win, the word was " + guess_word + "!")
答案 0 :(得分:0)
guess_word = "Giraffe"
guess = ""
guess_count = 0
guess_limit = 4
out_of_guesses = False
Question = input("Do you want to change guess word?")
if Question == "Yes":
guess_word = input("Please input new word:")
while guess != guess_word and not out_of_guesses:
if guess_count < guess_limit:
guess = input("Please make a guess: ")
guess_count = guess_count + 1
else:
out_of_guesses = True
if out_of_guesses:
print("Out of Guesses, You Lose")
else:
print("You win, the word was " + guess_word + "!")
超级简单!只要更改猜词,就消除所有重复的猜想逻辑。没必要。
答案 1 :(得分:0)
根据经验,当您知道应该停止代码的上限时,应该使用for
循环。当您删除一些不必要的变量时,它也使内容更清晰。
guess_word = "Giraffe"
guess_limit = 4
answer = input("Do you want to change guess word?").lower()
if answer == "yes":
guess_word = input("Please input new word:")
if answer == 'no':
for i in range(guess_limit):
guess = input("Please make a guess: ")
if guess == guess_word:
print("You win, the word was " + guess_word + "!")
break
if i == guess_limit - 1:
print("Out of Guesses, You Lose")
答案 2 :(得分:0)
您可以如下简化此代码。仅在question == Yes
时设置猜测词。然后运行循环,同时仍然有猜测。这利用了以下事实:如果int
不是True
,则将其视为0
,因此,尽管有猜测,但循环条件将被评估为True
。 guesses
为0
后,while循环条件的值为False
,循环将终止。
在循环中,我们检查输入是否与单词匹配,如果匹配,则打印“ You win ...”,然后break
循环。如果输入与单词不匹配,则我们将猜测计数减少1,然后循环再次开始。
当guesses
到达0
时,循环将终止。仅当循环终止而没有中断时才执行循环的else
条件。因此,如果他们获胜,我们将调用break,否则不会执行循环的else。但是,如果他们用完了猜测,循环将成功终止而不会中断,否则将运行语句并显示“ You ran out ...”。
guess_word = "Giraffe"
guesses = 4
Question = input("Do you want to change guess word?")
if Question == "Yes":
guess_word = input("Please input new word:")
while guesses:
if input("Please make a guess: ") == guess_word:
print("You win, the word was " + guess_word + "!")
break
guesses -= 1
else:
print("You ran out of guesses so you lose")