What is the best way to make a guessing loop in python? - python

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

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

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

Related

How do I store the results of a function into a list of some sort over time in Python?

So I'm refreshing what little I knew of Python before and playing around with some beginner projects. I'm toying arond with it now, and I'm just trying to learn and see what I can do. I made a "Guessing Game" and turned it into a function. I want to store these reults in a list each time it is used. I want the results to automatically go to the list when the game is completed and then to be able to print the list when desired.
I'm not sure if I need to create a new function for this, or if I should be creating this within my current "guessing_game" function. I've tried to create a list previously, but I'm not sure how to create and store the variable of the game result in order to add it into the list. I feel like this is probably a fairly simple problem, so I apologize if this is a dumb question.
def guessing_game():
import random
number = random.randint(1, 1000)
player_name = input("Enter name ")
number_of_guesses = 0
print('Howdy' + player_name + "Guess a number between 1 and 1000: ")
while number_of_guesses < 10:
guess = int(input())
number_of_guesses += 1
if guess < number:
print("Too Low, Joe")
if guess > number:
print("Too high, Sly")
if guess == number:
break
if guess == number:
print("You got it, Bobbit, in " + str(number_of_guesses) + " tries")
else:
print(" Well, yer were close, Stofe. Shoulda guessed " + str(number))
print(guessing_game())
You can create a list inside of the function, and then everytime they guess, you can store the guess inside the list. At the end, we can print the list.
def guessing_game():
import random
number = random.randint(1, 1000)
player_name = input("Enter name: ")
number_of_guesses = 0
guesses = []
print('Howdy ' + player_name + " Guess a number between 1 and 1000: ")
while number_of_guesses < 10:
guess = int(input())
guesses.append(guess)
number_of_guesses += 1
if guess < number:
print("Too Low, Joe")
if guess > number:
print("Too high, Sly")
if guess == number:
break
if guess == number:
print("You got it, Bobbit, in " + str(number_of_guesses) + " tries")
else:
print(" Well, yer were close, Stofe. Shoulda guessed " + str(number))
print("These were the numbers you guessed:")
for g in guesses:
print(g)
print(guessing_game())
What you need to do is create a list with something like val = []. I added it into the code and also added a formatting piece so it looks nice.
def guessing_game():
import random
guesses = []
number = random.randint(1, 1000)
guess = number / 2
player_name = input("Enter name ")
number_of_guesses = 0
print(f'Howdy {player_name}. Guess a number between 1 and 1000: ')
while number_of_guesses < 10:
guess = int(input('> '))
guesses = guesses + [guess]
number_of_guesses += 1
if guess < number:
print("Too Low, Joe")
if guess > number:
print("Too high, Sly")
if guess == number:
break
formatted_guesses = ''
for _ in range(len(guesses)):
if _ != len(guesses) - 1:
formatted_guesses = formatted_guesses + str(guesses[_]) + ', '
else:
formatted_guesses = formatted_guesses + str(guesses[_]) + '.'
if guess == number:
print("You got it, Bobbit, in " + str(number_of_guesses) + " tries")
print(f'You guessed {formatted_guesses}')
else:
print("Well, yer were close, Stofe. Shoulda guessed " + str(number))
print(f'You guessed {formatted_guesses}')
guessing_game()

User will get different points depending on which try to get their question right

I am trying to create a score system for my game. For each of the three tries, the user will get different points for getting the question right. For example, if the user gets the question right on the first try, he or she will receive 3 points. If they get it right on the second try, they will receive two points (one point on the third try and zero points if they run out of the three tries). How would I be able to do this?
total_score = 0
correct_answer = 2004
print('What was the year when Arsenal last won the Premier League?')
try:
for x in range(1, 4):
user_guess = int(input(f'Attempt {x}. '))
if user_guess == correct_answer:
total_score += 1
print(f'Good job! Your current score {total_score}')
break
else:
print(f'Incorrect! {total_score}')
except(ValueError):
print('Enter a numerical value for year.')
Like this
total_score = 0
correct_answer = 2004
MAX_POINTS = 4
print('What was the year when Arsenal last won the Premier League?')
try:
for x in range(1, MAX_POINTS):
user_guess = int(input(f'Attempt {x}. '))
if user_guess == correct_answer:
total_score += MAX_POINTS - x
print(f'Good job! Your current score {total_score}')
break
else:
print(f'Incorrect! {total_score}')
except(ValueError):
print('Enter a numerical value for year.')
MUST READ THE COMMENTS TO UNDERSTAND HOW IT WORKS..
total_score = 0
correct_answer = 2004
user_guess = '' # A blank string for user response. Strings can be reassigned later.
print('What was the year when Arsenal last won the the Premier League?')
for x in range(1, 4):
try: # This is the actual place to use exception handling
user_guess = int(input('Attempt ' + str(x) + ': '))
except ValueError:
print('You did not enter a numerical value for year.')
break
if user_guess == correct_answer:
total_score += (4-x) # will add (4-1), (4-2), (4-3) in subsequent loop runs.
print('Good Job! Your Current score: ' + str(total_score))
break
else:
print('Uh oh! You didn\'t get that right. Current score: ' + str(total_score) + '. Try Again..')
if x == 3: # To check if the three attempts have been used or not.
print('Alas! You are out of attempts. Try back later')
break
else:
continue

Creating a guessing game in Python using while and for loops

I am trying to make a guess game. I've used while, if, elif, and else statements but I'm stuck on how to use for and while loops as well as randomizing single hints and single answers from a nested lists.
black_box = ["guam","lakers","flash","buddha","drake","fortnite","annabelle","xmen","mars","dad"]
nested_list = [["island","yigo","cocos","kelaguen"],["kobe","la","magic","lebron"],["scarlet","speedster","dc","ezra"], ["asiangod","meditation","monk","enlightenment"],["rapper","onedance","canadian","raptors"],["game","epic","notminecraft","dances"],["doll","conjuring","soultaker","creation"],["wolverine","mystique","magneto","apocalypse"],["red","fourth","planet","ares"], ["man","american","peter","lionking"]]
i = random.randint(0,9)
word = black_box[i]
hint = nested_list[i]
print("Guess the word with the following hint: ", hint, "you have 4 tries.")
numofguesses = 0
guess = input("What is the word? ")
while numofguesses < 4:
numofguesses = numofguesses + 1
if guess == word:
print("You win!")
option = input("Do you want to try again or quit? ")
if option == "try again":
print("")
elif option == "quit":
break
if guess != word:
print("Try again!")
guess = input("What is the word? ")
if guess != word:
print("Try again!")
guess = input("What is the word? ")
I expected to get a line of code that prints "Try again!" but it skipped and started to print "What is the word? " print("Guess the word with the following hint: ", hint, "you have 4 tries.") Originally, I used hint[i] which printed out only one hint in the nested list but then I tried to run the program again but I got an error saying, "list index is out of range.
Your condition checks and loops where not correct. Try the below code, it should work fine.
black_box = ["guam","lakers","flash","buddha","drake","fortnite","annabelle","xmen","mars","dad"]
nested_list = [["island","yigo","cocos","kelaguen"],["kobe","la","magic","lebron"],["scarlet","speedster","dc","ezra"], ["asiangod","meditation","monk","enlightenment"],["rapper","onedance","canadian","raptors"],["game","epic","notminecraft","dances"],["doll","conjuring","soultaker","creation"],["wolverine","mystique","magneto","apocalypse"],["red","fourth","planet","ares"], ["man","american","peter","lionking"]]
while True:
i = random.randint(0, 9)
word = black_box[i]
numofguesses = 0
while numofguesses < 4:
hint = nested_list[i][numofguesses]
print("Guess the word with the following hint: ", hint, ". You have ", 4 - numofguesses, " tries!")
guess = input("What is the word? ")
numofguesses = numofguesses + 1
if guess == word:
print("You win!")
break
if guess != word:
print("Try again!")
option = input("Do you want to try again or quit? ")
if option == "try again":
print("")
else:
break

Breaking a loop for basic python

I have been working on this for a while now. I have been able to get parts of this to work, but never the whole thing. The end goal is to loop the user back into another game if they so choose. I think the issue is with my break statement, but I am not sure how to route around it. I have included all my code so that any mistakes can be found. Apologies if this has already been answered, I couldn't find a page with this kind of problem.
def game():
import random
from random import randint
n = randint(1, 10)
print('Enter a seed vlaue: ')
the_seed_value = input(' ')
random.seed(the_seed_value)
guessesTaken = 0
print("what is your name?")
myName = input("")
guess = int(input("Enter an integer from 1 to 99: "))
while n != "guess":
if guess < n:
print ("guess is low")
guessesTaken = guessesTaken + 1
guess = int(input("Enter an integer from 1 to 99: "))
elif guess > n:
print ("guess is high")
guessesTaken = guessesTaken + 1
guess = int(input("Enter an integer from 1 to 99: "))
else:
print ("Congradulations " + myName + " you guessed it in " + str(guessesTaken) + " guesses!")
break
print('Want to play agian? y/n')
answer = input(" ")
if answer == "n":
print ("Ok, See you next time!")
elif answer == "y":
print("Starting new game!")
game()
def main():
game()
if __name__ == "__main__":
main()
For one, #kerwei notes correctly that your while line has an issue, and needs to be changed from while n != "guess": to while n != guess:.
For two, your while loop is satisfied when the player guesses correctly, bypassing the Congrats line.
Since the game is currently structured to stay in the loop until the player guesses correctly, a simple fix would be to remove the else: line from the loop and place the victory statement afterwards. That is,
def game()
...
while n != guess:
if guess < n:
...
elif guess > n:
...
print('Congrats!')
print('play again?')
...

How do I get this game to end when the input is no without going back to the top?

How do I get this game to end when the input is no without going back to the top and looping through or getting an error code? Note I put "End" in so that it would not iterate again
import random
it's a simple guessing game that I want to start over if yes but end if no
def main():
y_games = 2
for y in range(y_games):
play_guessingGame_()
def play_guessingGame_():
guessesTaken = 0
print('Hello Friend,\n')
print('What is your name?\n')
name = input()
print(name + ' ,It is good to meet you!\n')
print("Let's play a game!\n ")
print('I am thinking of a number between 1 and 10. . . what is my number?\n')
try:
answer = random.randint(1,10)
while guessesTaken < 5:
print("Start guessing!\n")
guess = input()
guess = int(guess)
guessesTaken = guessesTaken + 1
if guess > answer:
print('Too high! Try again!\n')
elif guess < answer:
print('Too low! Try again!\n')
elif guess == answer:
break
while guess == answer:
guessesTaken = str(guessesTaken)
if guessesTaken == str(1):
print('AND ON THE FIRST TRY!!! IMPRESSIVE!!!!')
print('There is no beating you\n')
break
if guessesTaken > str(1):
print('Good job! You guessed my number in ' + guessesTaken + ' guesses')
print('There is no beating you\n')
break
if guess != answer:
print("I'm sorry, you have run out of guess.\n")
print('Better luck next time!\n')
except ValueError:
print('Please enter whole numbers only')
print('\nDo you want to try again? ')
response = input()
if response == 'yes':
print("Great! Let's do this!")
if response == 'no':
print('\nWell, all good things must come to end!')
Exit
main()
i added import random to your code and also changed Exit to exit() and there was no error and the game performed right, i hope i got your problem right..

Categories

Resources