Python Return Eval Value Within Function?
Solution 1:
You define a function called input
in the first line that takes zero arguments and then when you call the input
function later (which I assume you intended it to call the one that comes with Python and may have accidentally overridden) you pass it one variable.
# don't try to override the buil-in function
def input_custom():
h = eval(input("Enter hours worked: \n"))
return h
def main():
hours = input_custom()
print(hours)
main()
Solution 2:
input()
is the name of a builtin Python function.
In your code, you override it, which is definitely not a good idea. Try naming your function something else:
def get_hours():
h = eval(input("Enter hours worked: \n"))
return h
def main():
hours = get_hours()
print(hours)
main()
Solution 3:
Change your input function with a different name since input is a method in python.
def inputx():
h = eval(input("Enter hours worked: \n"))
return h
def main():
hours = inputx()
print(hours)
main()
Solution 4:
I can't replicate your exact error - instead I get:
TypeError: input() takes no arguments (1 given)
But, your error is likely caused by the same thing - when you name your function input
, you shadow the built-in input
: Python can't see both, even though yours doesn't expect a prompt. If you name yours myinput
instead, Python can tell the difference:
def myinput():
h = eval(input("Enter hours worked: \n"))
return h
def main():
hours = myinput()
print(hours)
main()
Solution 5:
Other answers have covered a lot.. I would just like add some thoughts to it. First of all your function name input is overriding the python builtin function
so first of all
def my_input():
return input("Enter hours worked: ")
print my_input()
This should suffice.
Concept:
Now if you are using Python 2.X version then there is no need for eval.
input(): Python by default evaluates the input expression if it is recognized by python.
raw_input(): Here the input is taken as a string which needs to be evaluated.
In case of Python3.x:
input() behaves like raw_input() and raw_input() is removed.
So your code should be
def my_input():
return float(input("Enter hours worked: "))
print(my_input())
It is safer and better way to take inputs and also tells us why eval is not recommended.
You don't know what's gonna come through that door.
Thank you.
Post a Comment for "Python Return Eval Value Within Function?"