如何使猜词游戏的代码更短?

时间:2019-11-24 17:57:59

标签: python-3.x

我昨晚才开始学习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 + "!")

3 个答案:

答案 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,因此,尽管有猜测,但循环条件将被评估为Trueguesses0后,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")