Python返回函数内的eval值?

时间:2012-06-01 04:16:09

标签: python function eval

def input():
    h = eval(input("Enter hours worked: \n"))
    return h

def main():
    hours = input()
    print(hours)  
main()

正如你所知,我是Python的新手。我一直得到:“TypeError:input()只取1个参数(给定0)。”非常感谢任何帮助/解释 - 非常感谢你们!

4 个答案:

答案 0 :(得分:2)

在第一行中定义一个名为input的函数,该函数接受零参数,然后在稍后调用input函数时(我假设您打算调用Python附带的函数)可能会被意外覆盖)你传递一个变量。

# 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()

答案 1 :(得分:1)

input()是内置Python函数的名称。

在你的代码中,你覆盖它,这绝对不是一个好主意。尝试将您的功能命名为其他内容:

def get_hours():
    h = eval(input("Enter hours worked: \n"))
    return h

def main():
    hours = get_hours()
    print(hours)  

main()

答案 2 :(得分:1)

使用不同的名称更改输入函数,因为输入是python中的方法。

def inputx():
     h = eval(input("Enter hours worked: \n"))
     return h

 def main():
     hours = inputx()
     print(hours)

 main()

答案 3 :(得分:1)

我无法复制您的确切错误 - 而是我得到:

TypeError: input() takes no arguments (1 given)

但是,你的错误很可能是由同一件事引起的 - 当你命名你的函数input时,你会影响内置的input:Python看不到两者,即使你没有期待提示。如果您为自己命名myinput,Python可以说出不同之处:

def myinput():
    h = eval(input("Enter hours worked: \n"))
    return h

def main():
    hours = myinput()
    print(hours)  
main()
相关问题