Home > Mobile >  How to use python to workout a simple mathematical problem in python with random operations
How to use python to workout a simple mathematical problem in python with random operations

Time:02-11

This is my code for a calculator that randomly selects a operation and number in between 1-10 and then with that number and operation works out the answer.

https://i.stack.imgur.com/Nys19.png

Now heres what happens when I run the code and put in a number. It dosen't workout the question it tells you the question. How do I make it answer the question.

https://i.stack.imgur.com/dLmaJ.png

Thank You if you help me

CodePudding user response:

You need to tell python to do something with each type of operation.

e.g.

operations = [' ','-']
operation = random.choice(operations)

if operation == ' ':
    answer = mynumber   yournumber

if operation == '-':
    answer = mynumber - yournumber;

print(mynumber,operation,yournumber,'=',answer)

You would need an if statement for each operation.

A more compact and flexible approach (although more advanced) would be

ops = {' ':(lambda x,y:x y),'-':(lambda x,y:x-y)}

op = random.choice(list(ops.keys()))

print(yournumber,op,mynumber,"=",ops[op](yournumber,mynumber))

As long as you have operations that take two inputs, you can extend the list of operations infinitely without having to change the rest of the code at all.

CodePudding user response:

In your case, it is safe to use otherwise unsafe function eval for this.

Since the user can only control a number (which is actually converted to int, not just assumed to be a number), he can't enter any code to evaluate.

answer = eval(f"{yournumber} {operation} {mynumber}")

This will create string like 123 4 and then evaluate it.

THIS IS NOT A GENERAL ADVICE, supplying eval with user input might cause a vulnerability which just happened to be impossible in your example

  • Related