python - Parsing a addition/subtraction/multiplication/division sign from a string -


i went through lesson of creating simple calculator using python, , i'm trying simplify it. issue follows: know possible parse string (number) float using "float()", i'm trying parse addition/subtraction/multiplication/division sign string float or integer or other format perform action. here's sample of i'm trying do:

while true:     user_input = input("""         quit - exit program         add - addition         sub - subtraction         mul - multiplication         div - division         please choose function:""")     actions = ("+-*/")     user_input_1 = float(input("first number:"))     user_input_2 = float(input("second number:"))     operation = user_input_1 float(action) user_input_2     if user_input == "add":         action = actions[0]         answer = operation         print (answer) 

if user_input "add" user_input_1 "5" user_input_2 "7" print(answer) should result in 12

this first part of code, , i'm getting syntax error. issue inability parse addition sign using "float()". there way of parsing signs?

even though should posting full traceback, syntaxerror comes line:

operation = user_input_1 float(action) user_input_2

it neither valid python expression nor statement.

a solution doesn't involve eval: can use operator module , dictionary "sign" operator itself, seen in basic (and error prone) example:

import operator  operations_dict = {'+': operator.add,                    '-': operator.sub} # extend other operators see fit  = float(input('first num')) b = float(input('second_num')) sign = input('operator') print(operations_dict[sign](a, b)) >> first num    1 >> second num    2 >> operator    + >> 3.0 

Comments

Popular posts from this blog

sql - invalid in the select list because it is not contained in either an aggregate function -

Angularjs unit testing - ng-disabled not working when adding text to textarea -

How to start daemon on android by adb -