Home > Net >  What is the best way to make a guessing loop in python?
What is the best way to make a guessing loop in python?

Time:01-13

Basically I'm trying to make a guessing game. There are 3 questions and you have 3 guesses for every question. The problem is I'm bad at coding, this is only my first time.

    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')

This code kind of works, but only if you get the answer wrong 2 times in a row for every question lol. I also haven't thought of a way to implement a score keeper yet (at the end I want it to say how many points you got out of 3.) The code also is obviously not done. Basically, my questions are: How come when I get the answer wrong once and then get it right on the second try it says that it took 3 tries? And if you get the answer right on the first or second try how can I make it so it ignores the remaining tries you have left? This is the error code for example if I get it right on the second try:

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

CodePudding user response:

Don't use a different variable to keep track of each guess, instead just use one variable, and continually update it using input(). Then you can check it over and over again, without writing a whole mess of if-else statements. For keeping track of the number correct, you can use a variable, and increment it every time a correct answer is entered.

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.')

CodePudding user response:

By utilizing the data structures within Python and a couple of functions, you can simplify your code considerably as shown below:

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}')  

The above approach allows you to extend the question repertoire as well as provide a different number of max tries by question.

simply execute playGame() to run the game

  •  Tags:  
  • Related