lundi 26 janvier 2015

Python mathematics within variable

My Python code needs to be able to randomly generate a number between 1 and 3 to determine what function to perform (addition, multiplication or subtraction). That works fine. I randomly generate two numbers and need to get this random function. So it would be like a basic maths sum like 3 + 6 = 9. The 3 would be stored as number1 (and randomly generated). The + would be stored as function and would also be randomly generated. The 6 would be stored as number2 and also randomly generated.


The problem I am having is combining all the variables together and getting it to work out the maths.


So I could do the following: (the numbers entered would have been randomly generated)



number1 = 3
number2 = 8
function = 3 (for the purposes of this: addition)

function then is changed to "+"


I am left doing this:



answer = number1, function, number2


Which obviously doesn't work.


Relevant full code:



from random import randint #Allows for random numbers
import time #Allows you to wait
year = int(input("What year are you? "))

if year == 6:
#Do year 6 stuff
year = "6"
print("You are year", year)

function = randint(1,3)

if function == 1:
function = "*"
print("Multiplying")
elif function == 2:
function = "-"
print("Subtracting")
elif function == 3:
function = "+"
print("Addiding")
else:
print("Program did not work as intended, failed at function point.")

tester = 300

while tester > 20:
number1 = randint(1,20)
number2 = randint(1,20)
int(tester) = number1 , function , number2

time.sleep(2)

print("Number1:",number1)
print("Number2:",number2)
print("Answer:",tester)



elif year == 5:
#Do year 5 stuff
year = "5"
print("You are year", year)
elif year == 4:
#Do year 4 stuff
year = "4"
print("You are year", year)
elif year == 3:
#Do year 3 stuff
year = "3"
print("You are year", year)
elif year == 2:
#Do year 2 stuff
year = "2"
print("You are year", year)
else:
print("You do not classify for this quiz.")




Aucun commentaire:

Enregistrer un commentaire