lundi 9 mai 2016

How do I multiply a variable by a character in Python?

I was working on a project in Python, which involves randomly selecting a operator (multiplication, division, addition, and subtraction), and then performing that operation on two integers. So far, my code will randomly select the operator in the form of a char. What I am struggling with is actually doing the math. Here is my code:

from random import randint
inputA = 2
inputB = 3
output = 0

desiredOutput = 5;
#possible operations: addition, subtraction, multiplication, division

add = "+"
multiply = "*"
divide = "/"
subtract = "-"

#choose randomely between the four

chooser = randint(1,4)
chosen = add
if chooser == 1:
    chosen = add
if chooser == 2:
    chosen = multiply
if chooser == 3:
    chosen = divide
if chooser == 4:
    chosen = subtract

Now what I want to do is take Input A and respectively multiply, divide, add or subtract it (using the "chosen" operator") from Input B.

Thanks, Avidh




Aucun commentaire:

Enregistrer un commentaire