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
Related
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
How would I ask the user if they want to play and then start the simulation? And if they don't the program prints a goodbye message. And print the total number of times the coin was flipped at the end.
import random
def num_of_input():
userName = input("Please enter your name: ")
print("Hello " + userName + "!" + " This program simulates flipping a coin.")
while True:
try:
time_flip= int(input("How many times of flips do you want? "))
except:
print("Please try again.")
continue
else:
break
return time_flip
def random_flip():
return random.randint(0, 1)
def count_for_sides():
count_head=0
count_tail=0
times=num_of_input()
while True:
if count_head + count_tail == times:
break
else:
if random_flip()==0:
count_head+=1
else:
count_tail+=1
print()
print(str(count_head) + " came up Heads")
print(str(count_tail) + " came up Tails")
count_for_sides()
You can get input from the user before calling the count_for_sides method and call it if they opt in.
import random
def num_of_input():
userName = input("Please enter your name: ")
print("Hello " + userName + "!" + " This program simulates flipping a coin.")
while True:
try:
time_flip = int(input("How many times of flips do you want? "))
except:
print("Please try again.")
continue
else:
break
return time_flip
def random_flip():
return random.randint(0, 1)
def count_for_sides():
count_head=0
count_tail=0
times=num_of_input()
while True:
if count_head + count_tail == times:
break
else:
if random_flip()==0:
count_head+=1
else:
count_tail+=1
print()
print(str(count_head) + " came up Heads")
print(str(count_tail) + " came up Tails")
userWantsToPlay = input("Do you want to play this game? (Y/n): ")
if (userWantsToPlay == 'Y'):
count_for_sides()
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)
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
import random
def start():
print "\t\t***-- Please enter Y for Yes and N for No --***"
answer = raw_input("\t\t Would you like to play a Guessing Game?: ")
if answer == "Y"
or answer == "y":
game()
elif answer == "N"
or answer == "n":
end()
def end():
print("\t\t\t **Goodbye** ")
raw_input("\t\t\t**Press ENTER to Exit**")
def game():
print "\t\t\t Welcome to Williams Guessing Game"
user_name = raw_input("\n\t\t Please enter your name: ")
print "\n", user_name, "I am thinking of a number between 1 and 20"
print "You have 5 attempts at getting it right"
attempt = 0
number = random.randint(1, 20)
while attempt < 5:
guess = input("\t\nPlease enter a number: ")
attempt = attempt + 1
answer = attempt
if guess < number:
print "\nSorry", user_name, "your guess was too low"
print "You have ", 5 - attempt, " attempts left\n"
elif guess > number:
print "\nSorry ", user_name, " your guess was too high"
print "You have ", 5 - attempt, " attempts left\n"
elif guess == number:
print "\n\t\t Yay, you selected my lucky number. Congratulations"
print "\t\t\tYou guessed it in", attempt, "number of attempts!\n"
answer = raw_input("\n\t\t\t\tTry again? Y/N?: ")
if answer == "Y"
or answer == "y":
game()
elif answer == "N"
or answer == "n":
end()
start()
If you want the computer to guess your number, you could use a function like this:
import random
my_number = int(raw_input("Please enter a number between 1 and 20: "))
guesses = []
def make_guess():
guess = random.randint(1, 20)
while guess in guesses:
guess = random.randint(1, 20)
guesses.append(guess)
return guess
while True:
guess = make_guess()
print(guess)
if guess == my_number:
print("The computer wins!")
break
else:
print(guesses)
It's just a quick-and-dirty example, but I hope it gives you the idea. This way, the computer gets unlimited guesses, but you could easily change the while loop to limit its number of guesses.