How do I limit input attempts in python? - python

I am trying to limit the attempts in a quiz I am making, but accidentally created an infinte loop. What am I doing wrong here?
score = 0
print('Hello, and welcome to The Game Show')
def check_questions(guess, answer):
global score
still_guessing = True
attempt = 3
while guess == answer:
print('That is the correct answer.')
score += 1
still_guessing = False
else:
if attempt < 2:
print('That is not the correct answer. Please try again.')
attempt += 1
if attempt == 3:
print('The correct answer is ' + str(answer) + '.')
guess_1 = input('Where was Hitler born?\n')
check_questions(guess_1, 'Austria')
guess_2 = int(input('How many sides does a triangle have?\n'))
check_questions(guess_2, 3)
guess_3 = input('What is h2O?\n')
check_questions(guess_3, 'water')
guess_4 = input('What was Germany called before WW2?\n')
check_questions(guess_4, 'Weimar Republic')
guess_5 = int(input('What is the minimum age required to be the U.S president?\n'))
check_questions(guess_5, 35)
print('Thank you for taking the quiz. Your score is ' + str(score) + '.')

Here is how you should handle it. Pass both the question and the answer into the function, so it can handle the looping. Have it return the score for this question.
score = 0
print('Hello, and welcome to The Game Show')
def check_questions(question, answer):
global score
for attempt in range(3):
guess = input(question)
if guess == answer:
print('That is the correct answer.')
return 1
print('That is not the correct answer.')
if attempt < 2:
print('Please try again.')
print('The correct answer is ' + str(answer) + '.')
return 0
score += check_questions('Where was Hitler born?\n', 'Austria')
score += check_questions('How many sides does a triangle have?\n', '3')
score += check_questions('What is H2O?\n', 'water')
score += check_questions('What was Germany called before WW2?\n', 'Weimar Republic')
score += check_questions('What is the minimum age required to be the U.S president?\n', '35')
print(f"Thank you for taking the quiz. Your score is {score}.")

Related

Python if and else statement not expected output

I am trying to make an animal quiz using python 3.9. On one of the questions getting it wrong 3 times doesn't start a new question like it should. Instead it is just blank. On the person's first and second attempt everything works smoothly. Any and all help is appreciated. Here is my code:
def check_guess(guess, answer):
global score
global name
still_guessing = True
attempt = 0
while still_guessing and attempt < 3:
if guess == answer:
print('Correct wow, i expected worse from someone named %s' % name)
if attempt == 0:
score = score + 3
elif attempt == 1:
score = score + 2
elif attempt == 2:
score = score + 1
still_guessing = False
elif attempt <= 1:
print('HAAAAAAAAAAAAAAAAAAAAAAAAAAAA IMAGINE NOT GETTING THAT RIGHT!!!')
print('L bozo + ratio')
guess = input('Try again ')
attempt = attempt + 1
if attempt == 3:
print('the correct answer was %s' % answer)
print('There is always next time!!')
still_guessing = False
score = 0
print('Welcome to the animal quiz')
print()
print('In this game you will have to guess the animal')
name = input('What is your name? ')
print('Cool name, I feel like i heard of it before hmmm %s..' % name)
print()
print('Enough stalling onto the game!!!')
guess1 = input('Which bear lives in the north pole ')
check_guess(guess1.strip().lower(), 'polar bear')
You have to put the if attempt == 3 in your while loop, because the loop while run infinitely until the guess is right, so when attempt's value is 3, it will do nothing because it is still in a loop and there is no if statement telling it what to do once the value is 3.
EDIT: Also change the loop conds to still guessing and attempt <= 3
attempt = 0
def check_guess(guess, answer):
global score
global name
global attempt
still_guessing = True
while still_guessing and attempt <= 3:
print(f"attempt {attempt}")
if attempt == 2:
print('the correct answer was %s' % answer)
print('There is always next time!!')
still_guessing = False
else:
print('HAAAAAAAAAAAAAAAAAAAAAAAAAAAA IMAGINE NOT GETTING THAT RIGHT!!!')
print('L bozo + ratio')
guess = input('Try again ')
attempt = attempt + 1
if guess == answer:
print('Correct wow, i expected worse from someone named %s' % name)
if attempt == 0:
score = score + 3
elif attempt == 1:
score = score + 2
elif attempt == 2:
score = score + 1
still_guessing = False
I think the elif bellow should evaluate <= 2, not 1:
elif attempt <= 2:
But than the last 'Try again' message is still printed. You can solve that putting an attempt check condition right before the 'Try again' message. In case the condition evaluate to True, you break the loop:
elif attempt <= 2:
print('HAAAAAAAAAAAAAAAAAAAAAAAAAAAA IMAGINE NOT GETTING THAT RIGHT!!!')
print('L bozo + ratio')
attempt = attempt + 1
if attempt > 2:
break
guess = input('Try again ')
Remember to adjust you While condition in this case, as the attempt check is not necessary anymore.
If I may, I did some refactoring in the code, so you can check out other ways to achieve the same goal.
def check_guess(guess, answer, attempts):
global score
global name
while True:
if guess == answer:
print('Correct wow, i expected worse from someone named %s' % name)
score = [0, 1, 2, 3]
final_score = score[attempts]
print(f'Score: {final_score}')
break
attempts -= 1
if attempts == 0:
print('the correct answer was %s' % answer)
print('There is always next time!!')
break
print('HAAAAAAAAAAAAAAAAAAAAAAAAAAAA IMAGINE NOT GETTING THAT RIGHT!!!')
print('L bozo + ratio')
guess = input('Try again ')
score = 0
print('Welcome to the animal quiz')
print()
print('In this game you will have to guess the animal')
name = input('What is your name? ')
print('Cool name, I feel like i heard of it before hmmm %s..' % name)
print()
print('Enough stalling onto the game!!!')
guess1 = input('Which bear lives in the north pole ')
check_guess(guess1.strip().lower(), 'polar bear', attempts=3)
I notice some mistakes.
First, you don't need if attempt == 3 or 2 because you are using a while loop (while loop is based on the condition at first).
Second, it is better to integrate "break" to not have an infinite loop.
While loop starts from 0 and ends at 2 (takes 3 values).
I rewrote the code, for you.
def check_guess(guess, answer):
global score
global name
still_guessing = True
attempt = 0
while still_guessing and attempt < 2:
if guess == answer:
print('Correct wow, i expected worse from someone named %s' % name)
if attempt == 0:
score = score + 3
elif attempt == 1:
score = score + 2
elif attempt == 2:
score = score + 1
still_guessing = False
elif attempt <= 1:
print('HAAAAAAAAAAAAAAAAAAAAAAAAAAAA IMAGINE NOT GETTING THAT RIGHT!!!')
print('L bozo + ratio')
guess = input('Try again ')
attempt = attempt + 1
break
print('the correct answer was %s' % answer)
print('There is always next time!!')
still_guessing = False
To test the code add print("pass OK")
score = 0
print('Welcome to the animal quiz')
print()
print('In this game you will have to guess the animal')
name = input('What is your name? ')
print('Cool name, I feel like i heard of it before hmmm %s..' % name)
print()
print('Enough stalling onto the game!!!')
guess1 = input('Which bear lives in the north pole ')
check_guess(guess1.strip().lower(), 'polar bear')
print("pass OK")
Don't forget to upvote :) (Ramadan Karim!!!)
in your while loop
'attempt' never become 3, so the code can't jump to the next part if attmpt == 3
so in the while loop, the elif condition should be elif attempt <= 2: then attempt = attempt + 1 can reach 3
Use below code it works for me .
def check_guess(guess, answer):
global score
global name
still_guessing = True
attempt = 0
while still_guessing and attempt < 3:
if guess == answer:
print('Correct wow, i expected worse from someone named %s' % name)
if attempt == 0:
score = score + 3
elif attempt == 1:
score = score + 2
elif attempt == 2:
score = score + 1
still_guessing = False
elif attempt <= 2:
print('HAAAAAAAAAAAAAAAAAAAAAAAAAAAA IMAGINE NOT GETTING THAT RIGHT!!!')
print('L bozo + ratio')
guess = input('Try again ')
attempt = attempt + 1
if attempt == 3:
print('the correct answer was %s' % answer)
print('There is always next time!!')
still_guessing = False
score = 0
print('Welcome to the animal quiz')
print()
print('In this game you will have to guess the animal')
name = input('What is your name? ')
print('Cool name, I feel like i heard of it before hmmm %s..' % name)
print()
print('Enough stalling onto the game!!!')
guess1 = input('Which bear lives in the north pole ')
check_guess(guess1.strip().lower(), 'polar bear')
I have change 1 into 2.

python guess game: help the player on the correct answer

hellow, I'm confused about writing this exercise from my book, can you please help me.
So far I have managed to write this amount:
import random
def main():
again = 'y'
number_of_guesses = 0
while again =='y':
print('guess the number game')
print(' ')
print('Guess my number between 1 and 1000 with the fewest guesses: ')
x = random.randrange(1,1000)
guess = int(input())
while guess !='':
if guess < x:
print('Your guess is too low , try again')
guess = int(input())
elif guess > x:
print('Your guess is too high , try again')
guess = int(input())
elif guess == x:
print('Congratulations! You guessed the number')
print('Do you want to repeat?')
print('if you want do, type y, else type the n')
number_of_guesses += 1
again = str(input(''))
break
else:
print('Error/!\, your enter is wrong:')
main()
The main text of the question: as appropriate to help the player “zero in” on the correct answer, then prompt the user for the next guess. When the user enters
the correct answer, display "Congratulations. You guessed the number!", and allow the
user to choose whether to play again.
your code is all ok! What's the deal? Check the indentations if still wrong
I think you already solve the problem, where exactly you need help?
And instead of putting
while guess !+ '':
I would put
while True:
You have only multiple indentation errors. Fixed version would be as follows:
import random
def main():
again = 'y'
number_of_guesses = 0
while again =='y':
print('guess the number game')
print(' ')
print('Guess my number between 1 and 1000 with the fewest guesses: ')
x = random.randrange(1,1000)
guess = int(input())
while guess !='':
if guess < x:
print('Your guess is too low , try again')
guess = int(input())
elif guess > x:
print('Your guess is too high , try again')
guess = int(input())
elif guess == x:
print('Congratulations! You guessed the number')
print('Do you want to repeat?')
print('if you want do, type y, else type the n')
number_of_guesses += 1
again = str(input(''))
break
else:
print('Error/!\, your enter is wrong:')
main()

How can I get two variables to hold the amount of higher than and lower than guesses?

I am creating a game in which the computer selects a random number 1-10
Then the user guesses the number until they get it right.
The trouble I am having is that when the users enter the wrong answer the variables high or low should be updated, but it just continues looping until the user does enter the right answer. Which causes high and low to always be at 0.
Any ideas? I know there is probably something wrong with the way I am looping?
Any pushes in the right direction would be great!
# module to generate the random number
import random
def randomNum():
selection = random.randint(0,9)
return selection
# get the users choices
def userGuess():
correct = True
while correct:
try:
userPick = int(input('Please enter a guess 1-10: '))
if userPick < 1 or userPick >10:
raise ValueError
except ValueError:
print('Please only enter a valid number 1 - 10')
continue
return userPick
# define main so we can play the game
def main():
correctNum = randomNum()
guess = userGuess()
high = 0
low = 0
if guess != correctNum:
print('uhoh try again!')
guess=userGuess()
elif guess > correctNum:
print('That guess is too high!')
high = high + 1
elif guess < correctNum:
print('That guess is too low')
low = low + 1
else:
print('You win!')
# the outcome of the game:
print('Guesses too high:', high)
print('Guesses too low:',low)
print('Thank you for playing!')
main()
Try modifying your main function :
def main():
correctNum = randomNum()
guess = userGuess()
high = low = 0 # nifty way to assign the same integer to multiple variables
while guess != correctNum: # repeat until guess is correct
if guess > correctNum:
print('That guess is too high!')
high = high + 1
else:
print('That guess is too low')
low = low + 1
print('Try again!')
guess=userGuess()
print('You win!')
# the outcome of the game:
print('Guesses too high:', high)
print('Guesses too low:',low)
print('Thank you for playing!')
Also, be careful with random.randint(0,9) : this will give a number between 0-9 (including 0 and 9, but never 10)!
You want to be doing random.randint(1, 10)
# module to generate the random number
import random
def get1to10():
selection = random.randint(1,10)
return selection
# get the users choices
def userGuess():
correct = True
while correct:
try:
userPick = int(input('Please enter a guess 1-10: '))
if userPick < 1 or userPick >10:
raise ValueError
except ValueError:
print('Please only enter a valid number 1 - 10')
continue
return userPick
# define main so we can play the game
def main():
correctNum = get1to10()
guess = 0
high = 0
low = 0
# use a while loop to collect user input until their answer is right
while guess != correctNum:
guess = userGuess()
# use if statements to evaluate if it is < or >
if guess > correctNum:
print('This is too high!')
high = high + 1
continue
# use continue to keep going through the loop if these are true
elif guess < correctNum:
print('this is too low!')
low = low + 1
continue
else:
break
# the outcome of the game:
print('----------------------')
print('Guesses too high:', high)
print('Guesses too low:',low)
print('The correct answer was:', '*',correctNum,'*', sep = '' )
print('Thank you for playing!')
print('---------------------')
main()
I found this solution to work well for what I needed!
Thank you everyone who answered this post!
You can try using a dictionary:
guesses = {'Higher': [],
'Lower': [],
'Correct': False,
} # A Dictionary variable
def add_guess(number, correct_number):
if number > correct_number:
guesses['Higher'].append(number)
elif number < correct_number:
guesses['Lower'].append(number)
else:
guesses['Correct'] = True
return guesses
add_guess(number=5, correct_number=3) # Higher
add_guess(10, 3) # Higher
add_guess(2, 3) # Lower
# Correct is False, and higher has the numbers (10, 5) while lower has the numbers (2)
print(guesses)
add_guess(3, 3) # Correct should now be True
print(guesses)
This, of course, isn't the entire code but should point you in the right direction. There is a ton of resources on python dictionaries online.

Implementing Cows and Bulls game

I have to code the Cows and Bulls game in which I have to generate 4 random number and ask the users to guess it. I have been trying for the past few hours to code it but can't seem to come up with a solution.
The output I want is:
Welcome to cows and Bulls game.
Enter a number:
>> 1234
2 Cows, 0 Bulls.
>> 1286
1 Cows, 1 Bulls.
>> 1038
Congrats, you got it in 3 tries.
So far, I have got this:
print("Welcome to Cows and Bulls game.")
import random
def number(x, y):
cowsNbulls = [0, 0]
for i in range(len(x)):
if x[1] == y[i]:
cowsNbulls[1] += 1
else:
cowsNbulls[0] += 1
return cowsNbulls;
x = str(random.randint(0, 9999))
guess = 0
while True:
y = input("Enter a number: ")
count = number(x, y)
guess += 1
print(str(count[0]), "Cows.", str(count[1]), "Bulls")
if count[1] == 4:
False
print("Congrats, you done it in", str(guess))
else:
break;
And the output is:
Welcome to Cows and Bull game.
Enter a number: 1234
4 Cows, 0 Bulls.
It would not continue. I was just wondering what the problem is.
Try this:
print(str(count[0]), "Cows.", str(count[1]), "Bulls")
if count[0] == 4:
print("Congrats, you done it in", str(guess))
break
You want to break the while loop if the count equals 4, otherwise it should continue to run.
There are some things wrong with your code:
The while True statement has the same indent level as a function
Inside the while statement you use break which is why the statement only executes once if you fail to get the correct anwser the first time
"x & y" variables?? Please in the future use vars that make sense, not only to you, but to others
In the function "number" you have a this validation x[1] == y[i] this wont do anything, it will only compare the first char of the string
Below I made some repairs to your code, see if it's something like this that you are looking for:
import random
def number(rand_num, guess):
cowsNbulls = {
'cow': 0,
'bull': 0,
}
for i in range(len(rand_num)):
try:
if rand_num[i] == guess[i]:
cowsNbulls['cow'] += 1
else:
cowsNbulls['bull'] += 1
except:
pass
return cowsNbulls;
def game_start():
rand_number = str(random.randint(1, 9999))
tries = 0
locked = True
print("Welcome to Cows and Bulls game.")
while locked:
print(rand_number)
guess = input("Enter a number (Limit = 9999): ")
cows_n_bulls = number(rand_number, guess)
tries += 1
print(str(cows_n_bulls['cow']), "Cows.", str(cows_n_bulls['bull']), "Bulls")
if cows_n_bulls['cow'] == 4:
print("Congrats, you done it in", str(tries))
locked = False
game_start()

looking for advice for coding project

So as of right now the code needs to re-ask the problem given if the answer given was too high or too low. Also, if the answer is correct, it should tell them and then loop back to the question ('How many problems do you want?')
def main():
gamenumber = int(input("How many problems do you want?\n"))
count = 0
while count < gamenumber:
num_1 = randint(1,10)
num_2 = randint(1,10)
guess = int(input("What is " + str(num_1) + "x" + str(num_2) + "."))
answer = (num_1*num_2)
count += 1
for guess in range(1):
if guess == answer:
print (' Thats Correct!')
for guess in range(1):
if guess > answer:
print (' Answer is to high')
for guess in range(1):
if guess < answer:
print ('Answer is to low')
main()
First of all can you please check your code. You have used "guess" variable in the for loop. When the program is executed the value of guess is say 40(4X10). When for statement is executed the guess values becomes 0 because of that you are getting the output as low. Make sure u change the variable you use in for loop to "num" and then check your output.
Why are you using 3 for loops you can do that in single for loop.
Please find the below code:-
from random import randint
def main():
ans = 'y'
while ans != 'n':
gamenumber = int(input("How many problems do you want?\n"))
count = 0
while count < gamenumber:
num_1 = randint(1,10)
num_2 = randint(1,10)
guess = int(input("What is " + str(num_1) + "x" + str(num_2) + "."))
print(guess)
answer = (num_1*num_2)
print("=====>",answer)
count += 1
for num in range(1):
if guess == answer:
print (' Thats Correct!')
elif guess > answer:
print (' Answer is to high')
elif guess < answer:
print ('Answer is to low')
yes_no_input = str(input("Do you want to continue (y/n) ?"))
ans = accept_ans(yes_no_input)
if ans == 'n':
print("thanks for the test")
break;
def accept_ans(ans):
if not ans.isalpha():
print("Enter only y and n")
ans = str(input("Do you want to continue (y/n) ?"))
if ans == 'y' or ans == 'n':
return ans
if ans != 'y' or ans != 'n':
print("please enter y for YES and n for NO")
ans = str(input("Do you want to continue (y/n) ?"))
if ans != 'y' or ans != 'n':
accept_ans(ans)
if __name__ == '__main__':
main()
After
print("Thats correct")
you need to call the
main()
function again.

Categories