I want to make a game that will generate multipication equations. I want to make it that you will get a simple multipication equation (ex: 5*6) and when you answer it, the program will tell you if you are correct, and then will go to the next random equation. I know how to make it with a lot of different random numbers, but this will make the code very long and not ellegant. I need a way to generate two different random numbers every time, without having to make a data base of let's say 20 different random numbers. Does anyone know how to do it? Thanks!
This is the code I've wrote so far:
import random
import sys
import os
random_num1 = random.randrange(1, 10)
random_num2 = random.randrange(1, 10)
print(random_num1, 'X', random_num2, '=', )
def multiplication(random_num1, random_num2):
sumNum = random_num1 * random_num2
return sumNum
one = input()
if(int(one) == multiplication(random_num1, random_num2)):
print('true')
else:
print('false')
Put all of your code into a while loop that never ends using while True:
(and don't forget to move everything inside by one tab to the right).
It's advisable to move def multiplication
out of the while
loop though.
You could easily do it with a function and a while loop. Let's say, you want to play 10 times and want the score at the end.
def multiplication(random_num1, random_num2):
sumNum = random_num1 * random_num2
# Indentation fixed
return sumNum
def play() :
random_num1 = random.randrange(1, 10)
random_num2 = random.randrange(1, 10)
print(random_num1, 'X', random_num2, '=', )
one = input()
if(int(one) == multiplication(random_num1, random_num2)):
return 1
else:
return 0
if __name__ == '__main__' :
number_of_play = 10
cpt = 0
result = 0
while cpt < number_of_play :
cpt+=1
cpt += play()
print "Wow you perform {} out of {}".format(result, number_of_play)
Here it is a simple example made by me (EDITED with "try" statement):
from random import randint
while 1:
numA = randint(0,9)
numB = randint(0,9)
result = numA * numB
print("\nFirst number:", numA)
print("Second number:", numB)
while 1:
try:
userResult = int(input("Insert your multiplication result: "))
break
except:
print("Error! The given digit is not a number. Retry :")
if userResult == result:
print("Bravo! That's right!")
else:
print("Damn! That's wrong!")
I've tried to be as clear as possible. I hope it was useful for you.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.