【问题标题】:What is the best way to make a guessing loop in python?在 python 中进行猜测循环的最佳方法是什么?
【发布时间】:2022-01-12 19:37:41
【问题描述】:

基本上我正在尝试做一个猜谜游戏。有 3 个问题,每个问题你有 3 个猜测。问题是我不擅长编码,这只是我的第一次。

    print("Guessing Game")
player_name = input("Hi! What's your name? ")
number_of_guesses1 = 0
number_of_guesses2 = 0
number_of_guesses3 = 0
guess1 = input("What is the most popular car company in America? ")
while number_of_guesses1 < 3:
    number_of_guesses1 += 1
    if guess1 == ("Ford"):
        break

if guess1 == ("Ford"):
    print('You guessed the answer in ' + str(number_of_guesses1) + ' tries!')
else:
    guess2 = input("Try again:")
if guess2 == ("Ford"):
    print('You guessed the answer in ' + str(number_of_guesses1) + ' tries!')
else:
    guess3 = input("Try again:")
if guess3 == ("Ford"):
    print('You guessed the answer in ' + str(number_of_guesses1) + ' tries!')
else:
    print('You did not guess the answer, The answer was Ford')

guess1b = input("What color do you get when you mix red and brown?")

while number_of_guesses2 < 3:
    number_of_guesses2 += 1
    if guess1 == ("Maroon"):
        break
if guess1b == ("Maroon"):
    print('You guessed the answer in ' + str(number_of_guesses1) + ' tries!')
else:
    guess2b = input("Try again:")
if guess2b == ("Maroon"):
    print('You guessed the answer in ' + str(number_of_guesses1) + ' tries!')
else:
    guess3b = input("Try again:")
if guess3b == ("Maroon"):
    print('You guessed the answer in ' + str(number_of_guesses1) + ' tries!')
else:
    print('You did not guess the answer, The answer was Maroon')

这种代码是有效的,但前提是你每个问题都连续答错 2 次,哈哈。我还没有想到实现计分器的方法(最后我想让它说你从 3 中得到了多少分。)代码显然也没有完成。基本上,我的问题是:当我回答错误一次然后在第二次尝试时正确回答它说它需要 3 次尝试时,怎么会这样?如果你在第一次或第二次尝试中得到正确的答案,我怎样才能让它忽略你剩下的剩余尝试?这是错误代码,例如,如果我在第二次尝试时正确:

Traceback (most recent call last):
  File "main.py", line 20, in <module>
    if guess3 == ("Ford"):
NameError: name 'guess3' is not defined

【问题讨论】:

  • 欢迎来到Stack Overflow. 请注意这不是代码编写或辅导服务。我们可以帮助解决特定的技术问题,而不是对代码或建议的开放式请求。请编辑您的问题以显示您迄今为止尝试过的内容,以及您需要帮助的具体问题。请参阅How To Ask a Good Question 页面,详细了解如何最好地帮助我们。
  • 您需要让用户输入 inside while 循环。否则你只问他们一次。
  • @itprorh66 “我的问题是:为什么我一次答错了,然后第二次就答对了,它说它需要 3 次尝试?如果你在第一次或第二次尝试我怎样才能让它忽略你剩下的尝试?这是错误代码,例如,如果我在第二次尝试时正确:"

标签: python loops


【解决方案1】:

通过利用 Python 中的数据结构和几个函数,您可以大大简化代码,如下所示:

from collections import namedtuple

# Create a tuyple containing the Question, number of allowed tries and the answer
Question = namedtuple("Question", ["quest", 'maxTries', 'ans'])

def askQuestion(quest: str, mxTry: int, ans: str) -> int:
    """ Ask the question, process answer, keep track of tries, return score"""
    score = mxTry
    while score > 0:
        resp = input(quest)
        if resp.lower() == ans:
            print('Yes, you got it')
            break
        else:
            score -= 1
            print(f'Sorry {resp} is incorrect, try again')
    if score == 0:
        print("Too Bad, you didn't get the correct answer.")
        print(f"The correct answer is {ans}")
    return score  

def playGame():
    # Create a list of questions defiend using the Question structure defined above
    question_list =[Question('What is the most popular car company in America? ' , 3, 'ford'),
               Question("What color do you get when you mix red and brown?", 3, 'maroon')]
    
    plyr_score = 0
    for q in question_list:
        plyr_score += askQuestion(q.quest, q.maxTries, q.ans)
    print(f'Your final score is {plyr_score}')  

上述方法允许您扩展问题库并按问题提供不同的最大尝试次数。

只需执行playGame()即可运行游戏

【讨论】:

    【解决方案2】:

    不要使用不同的变量来跟踪每个猜测,而是只使用一个变量,并使用input() 不断更新它。然后你可以一遍又一遍地检查它,而不用写一大堆 if-else 语句。为了跟踪数字的正确性,您可以使用一个变量,并在每次输入正确答案时递增它。

    print("Guessing Game")
    player_name = input("Hi! What's your name? ")
    score = 0
    
    
    answer1 = "Ford"
    answer2 = "Maroon"
    
    guess = input("What is the most popular car company in America? ")
    number_of_guesses = 1
    while guess != answer1 and number_of_guesses < 3:
        guess = input("Try again: ")
        number_of_guesses += 1
    if guess == answer1:
        print('You guessed the answer in ' + str(number_of_guesses) + ' tries!')
        score += 1
    else:
        print('You did not guess the answer, The answer was Ford')
    
    guess = input("What color do you get when you mix red and brown? ")
    number_of_guesses = 1
    while guess != answer2 and number_of_guesses < 3:
        guess = input("Try again: ")
        number_of_guesses += 1
    if guess == answer2:
        print('You guessed the answer in ' + str(number_of_guesses) + ' tries!')
        score += 1
    else:
        print('You did not guess the answer, The answer was Maroon')
    
    print('You got ' + str(score) + ' out of 2 questions.')
    

    【讨论】:

    • 这太棒了,非常感谢。
    • 最后一件事,我怎样才能做到这一点,如果用户输入“ford”例如那不是大写的,它仍然会标记它是正确的?执行“if guess == str.lower()(answer1):”没有用。
    • @JosephAlexander 你必须把字符串的名字放在 .lower() 前面:if guess == answer1.lower()
    • 我试过了,但由于某种原因,代码出现了故障。这使得福特和福特在某种程度上都是错误的答案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-09-21
    • 1970-01-01
    • 1970-01-01
    • 2021-10-19
    • 2021-08-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多