math game not working - python

I made a function for a program I am making, It's a math game where you have to input an answer, and if the answer is right you win. I thought the game was simple, but for some reason, whenever you input the answer, the program says it's wrong, even if the answer is right.
def gameChoice():
print("what game do you want to play? A math game")
game_choice = input(">>")
if game_choice == 'math game':
number1 = random.randint(1, 30)
number2 = random.randint(1, 30)
answer = (number1 + number2)
print("%d + %d = %d" %(number1, number2, answer))
player_answer = input(">> ")
if player_answer == answer:
print("congrats, you got it right")
else:
print("sorry, try again")

Instead of int, you could use literal_eval (from the ast built-in). That will allow either a float or an int in case you want to support floats in the future. You'd also want some exception handling in case the user enters a string or just hits Enter.
Then, you'll want to loop until the user gets it right. One possible fix would be:
import random
from ast import literal_eval
def gameChoice():
print("what game do you want to play? A math game")
game_choice = input(">>")
if game_choice == 'math game':
number1 = random.randint(1, 30)
number2 = random.randint(1, 30)
answer = (number1 + number2)
while True:
print("%d + %d = %d" % (number1, number2, answer))
try:
player_answer = literal_eval(input(">> "))
except ValueError:
print('Please enter a number for the answer')
except SyntaxError:
print('Please enter an answer')
else:
if player_answer == answer:
break
else:
print("sorry, try again")
print("congrats, you got it right")

The code:
player_answer is a string
and
answer is an int
which makes the 2 never equal to each other try putting
player_answer = int(input(">> "))
this makes the input automatically a integer

Related

Can't find a way to incorporate addition, division, subtraction and multiplication inside of my small game

I am trying to use the variables user_ans_a, user_ans_s, user_ans_m and user_ans_d inside of my game as questions randomly chosen by python. My dilemma is coming from matching the randomly chosen variable to an answer coresponding to that variable. I want the user to be able to enter an anser to those questions.
import random
import re
while True:
score = 0
top = "--- Mathematics Game ---"
print(len(top) * "━")
print(top)
print(len(top) * "━")
print(" Type 'Play' to play")
start_condition = "Play" or "play"
def checkint(input_value):
while True:
try:
x = int(input(input_value))
except ValueError:
print("That was a bad input")
else:
return x
while True:
inp = input()
if inp == "Play":
break
else:
print("Try again")
if inp == "Play":
print("What's your name?")
name = input()
print(f"Hello {name}")
while True:
try:
no_of_rounds = int(input("how many rounds do you want to play? "))
break
except ValueError:
print('Please enter a number.')
for i in range(no_of_rounds):
ran_int1 = (random.randint(1,10))
ran_int2 = (random.randint(1,10))
answer_a = (ran_int1 + ran_int2)
answer_s = (ran_int1 - ran_int2)
answer_m = (ran_int1 * ran_int2)
answer_d = (ran_int1 / ran_int2)
user_ans_a = (f"What does {ran_int1} + {ran_int2} = ")
user_ans_s = (f"What does {ran_int1} - {ran_int2} = ")
user_ans_m = (f"What does {ran_int1} * {ran_int2} = ")
user_ans_d = (f"What does {ran_int1} / {ran_int2} = ")
if checkint(user_ans_a) == int(answer_a):
print(f"That was correct {name}.")
score = score+1
else:
print(f"Wrong {name}, the answer was {answer_a}, try again")
print(f"Score was {score}")
while True:
answer = str(input('Run again? (y/n): '))
if answer in ('y', 'n'):
break
print("invalid input.")
if answer == 'y':
continue
else:
print("Goodbye")
break

This program loops the same thing over and over again and I want it to do it once and continuing on to the other programs below the loop

When I run this, it just keeps on repeating itself asking for a number over and over again. I am a beginner at python so please don't judge.
import random
import time
while True:
guess = input("Please enter a lucky number between 1 to 10:\n")
number = random.randint(0, 10)
print ("Random number is " + str(number) + ":")
if guess == number:
print ("Awesome - You guessed correctly!")
answer = input('Would you like to try again? (y/n):\n')
def func():
if answer == 'n':
print ("Have a wonderful day!")
time.sleep(2)
else:
print("Good try, Would you like to play again? (y/n):")
func()
you can do it like this:
import random
import time
number = random.randint(0, 10)
while True:
guess = int(input("Please enter a lucky number between 1 to 10:\n"))
print ("Random number is " + str(number) + ":")
if guess == number:
print ("Awesome - You guessed correctly!")
answer = input('Would you like to try again? (y/n):\n')
if answer == 'n':
print ("Have a wonderful day!")
break
else:
print("generating new number...")
number = random.randint(0, 10)

Return to another part of a loop

I am learning python and I cannot figure out how to get back to a certain part of loop depending on the response.
If it reaches:
else :
print('Answer must be yes or no')
I want it to start back at:
print ("We are going to add numbers.")
I have tried several different suggestions I have seen on here, but they result in starting back at the very beginning.
My code:
import random
num1 = random.randint(1,100)
num2 = random.randint(1,100)
addition = num1 + num2
print("Hello. What is your name?")
name = str(input())
print ("Nice to meet you " + name)
print ("We are going to add numbers.")
print ("Does that sound good?")
answer = str.lower(input())
if answer == str('yes'):
print ('Yay!!')
print ('Add these numbers')
print (num1, num2)
numbers = int(input())
if numbers == addition:
print('Good Job!')
else:
print('Try again')
numbers = int(input())
elif answer == str('no'):
print ('Goodbye')
else :
print('Answer must be yes or no')
You need a loop that starts with the thing you want to get back to:
def start():
import random
num1 = random.randint(1, 100)
num2 = random.randint(1, 100)
addition = num1 + num2
print("Hello. What is your name?")
name = str(input())
print("Nice to meet you " + name)
while True:
print("We are going to add numbers.")
print("Does that sound good?")
answer = str.lower(input())
if answer == "no":
print("Goodbye")
return
elif answer == "yes":
break
else:
print('Answer must be yes or no')
print('Yay!!')
print('Add these numbers')
print(num1, num2)
# This following part might want to be a loop too?
numbers = int(input())
if numbers == addition:
print('Good Job!')
else:
print('Try again')
numbers = int(input())

How to generate a new arithmetic exercise in a quiz game

I'm writing a Python math game in which the program asks an addition question and the user has to get the right answer to continue. My question is, how can I make the program generate a new math problem when the user gets the last one correct?
import random
firstNumber = random.randint(1, 50)
secondNumber = random.randint(1, 50)
result = firstNumber + secondNumber
result = int(result)
print("Hello ! What\'s your name ? ")
name = input()
print("Hello !"+" "+ name)
print("Ok !"+" "+ name +" "+ "let\'s start !")
print("What is"+ " " + str(firstNumber) +"+"+ str(secondNumber))
userAnswer = int(input("Your answer : "))
while (True) :
if (userAnswer == result):
print("Correct")
print("Good Job!")
break
else:
print("Wrong\n")
userAnswer = int(input("Your answer : "))
input("\n\n Press to exit")
Implement the game with a pair of nested loops. In the outer loop, generate a new arithmetic problem. In the inner loop, keep asking the user for guesses until he either gives the right answer or decides to quit by entering a blank line.
import random
playing = True
while playing:
# Generate a new arithmetic problem.
a = random.randint(1, 50)
b = random.randint(1, 50)
solution = a + b
print('\nWhat is %d + %d? (to quit, enter nothing)' % (a, b))
# Keep reading input until the reply is empty (to quit) or the right answer.
while True:
reply = input()
if reply.strip() == '':
playing = False
break
if int(reply) == solution:
print('Correct. Good job!')
break
else:
print('Wrong. Try again.')
print('Thank you for playing. Goodbye!')
This should get you started. The getnumbers() returns two random numbers, just like in your script. Now just add in you game code. Let me know if you have questions!
import random
def getnumbers():
a = random.randint(1, 50)
b = random.randint(1, 50)
return a, b
print("Math Game!")
while True:
a, b = getnumbers()
# game code goes here
print("%d %d" % (a, b))
input()
This might do what you want:
import random
def make_game():
firstNumber = random.randint(1, 50)
secondNumber = random.randint(1, 50)
result = firstNumber + secondNumber
result = int(result)
print("What is"+ " " + str(firstNumber) +"+"+ str(secondNumber))
userAnswer = int(input("Your answer : "))
while (True) :
if (userAnswer == result):
print("Correct")
print("Good Job!")
break
else:
print("Wrong\n")
userAnswer = int(input("Your answer : "))
print("Hello ! What\'s your name ? ")
name = input()
print("Hello !"+" "+ name)
print("Ok !"+" "+ name +" "+ "let\'s start !")
while True:
make_game()
end = input('\n\n Press to "end" to exit or "enter" to continue: ')
if end.strip() == 'end':
break

Python: Number Guessing Game

Your program chooses the number to be guessed by selecting an integer at random in the range 1 to 1000 (inclusive). If the player's guess is incorrect, your program should loop until the player finally gets the number right. Your program should keep telling the player Too high or Too low to help the player “zero in” on the correct answer. After a game ends, the program should prompt the user to enter "y" to play again or "n" to exit the game.
My problem is how do you generate a new random integer each time they want to play again?
Here's my code.
import random
randomNumber = random.randrange(1, 1000)
def main():
print ""
number = input("I have a number between 1 and 1000. Can you guess my number? Please type your first guess: ")
guess(number)
def guess(number1):
correct = False
while not correct:
if number1 > randomNumber:
print "Too high. Try again."
print ""
elif number1 < randomNumber:
print "Too low. Try again."
print ""
elif number1 == randomNumber:
break
number1 = input ("What number do you guess? ")
if number1 == randomNumber:
playAagain = raw_input ("Excellent! You guessed the number! Would you like to play again (y or n)? ")
if playAagain == "y":
main()
main()
Take this line:
randomNumber = random.randrange(1, 1000)
and place it inside guess:
import random
def main():
print ""
number = input("I have a number between 1 and 1000. Can you guess my number? Please type your first guess: ")
guess(number)
def guess(number1):
#########################################
randomNumber = random.randrange(1, 1000)
#########################################
correct = False
while not correct:
if number1 > randomNumber:
print "Too high. Try again."
print ""
elif number1 < randomNumber:
print "Too low. Try again."
print ""
elif number1 == randomNumber:
break
number1 = input ("What number do you guess? ")
if number1 == randomNumber:
playAagain = raw_input ("Excellent! You guessed the number! Would you like to play again (y or n)? ")
if playAagain == "y":
main()
main()
Now, a new random integer will be created each time the function is called.
Put a loop in main() and initialize randomNumber at the beginning of the loop.
please try this remove four spaces starting from random to starting of while loop
import random
print " welcome to game of guessing "
print "you have 6 attempts"
num1 = random.randint(1,100)
print num1 # this is your computer generated number ( skip while running :only for test purpose)
num2 = num1+random.randint(1,15)
print " hint: number is close to " + str(num2)
count=1
while count<=6:
print " enter the number you think"
inputnum=raw_input()
if inputnum==str(num1):
print "congrats you guess the correct number"
break
elif inputnum<str(num1):
print " number is lower than correct one "
count=count+1
elif inputnum>str(num1):
print "number is greater than correct one"
count=count+1
else:
break
You just have to define your main() function like this.
def main():
global randomNumber
print ""
randomNumber = random.randrange(1, 1000)
number = input("I have a number between 1 and 1000. Can you guess my number? Please type your first guess: ")
guess(number)
And everything will be perfect. Hope this helps.

Categories

Resources