+ 1

Question about Functions in Python?

Hello everyone, I'm learning python through the course on this site. I'm trying to become better with functions and making my code shorter and more efficient. The only thing that I've made so far is the calculator used in the course which is coded with elif statements and user input: elif user_input == "add": num1 = float(input("Enter a number: ")) num2 = float(input("Enter another number: ")) result = str(num1 + num2) print("The answer is " + result) However, I thought instead of repeating the code to add and subtract and so on, I could create a function that asks the user to select an operator, and then plug that operator into the code to make it easier, like so: def my_func(op): num1 = float.input("Please enter your first number ") num2 = float.input("Please enter your second number ") print(num1 op num2) my_func Unfortunately, this doesn't work. Is there anyway this is possible, to use the function argument like that? Any help or education is appreciated. Thank you.

9th Mar 2018, 4:06 AM
Carter Walker
1 Resposta
+ 3
There is a built-in eval function in python: >>> x = 1 >>> eval('x+1') 2 NOTE: using eval with user input is almost always a BAD IDEA due to utter insecurity. That's why always at least chek user input for allowed keywords.
9th Mar 2018, 6:56 AM
strawdog
strawdog - avatar