Berke Can Berke Can - 1 year ago 57
Python Question

How to take input as operation

I'm trying to make a calculator but little bit different.
I'm thinking if a get input as operation like:

first_number = input('Type first number: ')
first_operation = input('Type your operation (+, -, *, /): ')
second_number = input('Type second number: ')
first_answer = input('Do you wanna stop here y/n: ')
if first_answer = "y":
print(int(first_number), str(first_operation), int(second_number))

At the moment, the program needs to make a problem with user's input. For example, if user types
for first number,
for first operation,
for second number. I can only write those inputs like
3 + 2
, but I want to solve after print answer.

Jim Jim
Answer Source

Grab the operations from the operator module and create a dictionary of the available operators:

>>> from operator import add, sub, mul, truediv
>>> ops = {'+': add, '-': sub, '*': mul, '/': truediv}

After doing this you can use first_operation as the key on ops, get the corresponding function for the operation and supply first_number and second_number as its arguments:

>>> first_number = int(input('Type first number: '))
>>> second_number = int(input('Type second number: '))
>>> first_operation = input('Type your operation (+, -, *, /): ')

Let's say we enter 5 and 10 and +, then:

>>> print(ops[first_operation](first_number, second_number))

Note, the numbers are wrapped in int before supplying them to the operator since they behave differently when of type str.

As a simple alternative, you could use literal_eval from the ast module, supplying it an expression as input:

>>> from ast import literal_eval
>>> first_number = input('Type first number: ')
>>> second_number = input('Type second number: ')
>>> first_operation = input('Type your operation (+, -, *, /): ')

Here you don't need to change anything to int, you just join all arguments and make a string of the overall expression and feed it to literal_eval for it to do its thing.

>>> literal_eval(" ".join([first_number, first_operation, second_number]))

In essence your call will look like:

>>> literal_eval('5 + 10')

With a result of 15, again.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download