尝试将原始输入与函数一起使用

2024-06-01 11:23:27 发布

您现在位置:Python中文网/ 问答频道 /正文

我是python新手,我正在尝试为一个带有原始输入和函数的程序编写一个命令类的东西。不知为什么它一直不起作用。这是我一直在测试的代码:

raw_input()

def test():
    print "hi, this will be amazing if it works"

Tags: 函数代码test命令程序inputrawdef
3条回答

raw_input将阻塞,直到您键入内容。当接收到换行符(用户按enter)时,该值将被返回并存储。似乎您从未试图调用函数test。也许你想试试这样的东西(如果你需要的话,我可以进一步解释)

name = raw_input("What is your name: ")

def test(username):
    print "Hi %s, this will be amazing if it works" % (username,)

test(name)

根据您的其他意见,这是一种安全的方法:

# Define two functions test() and other()
def test():
    print "OMG, it works..."

def other():
    print "I can call multiple functions"

# This will be to handle input for a function we don't have
def fail():
    print "You gave a bad function name.  I only know about %s" % (", ".join(funcs.keys()))

# This is a dictionary - a set of keys and values.  
# Read about dictionaries, they are wonderful.  
# Essentially, I am storing a reference to the function
# as a value for each key which is the value I expect the user to ender.
funcs = {"test": test, "other": other}

# Get the input from the user and remove any trailing whitespace just in case.
target = raw_input("Function to run? ").strip()

# This is the real fun.  We have the value target, which is what the user typed in
# To access the value from the dictionary based on the key we can use several methods.
# A common one would be to use funcs[target]
# However, we can't be sure that the user entered either "test" or "other", so we can 
# use another method for getting a value from a dictionary.  The .get method let's us
# specify a key to get the value for, as wel as letting us provide a default value if
# the key does not exist.  So, if you have the key "test", then you get the reference to 
# the function test.  If you have the key "other", then you get the reference to the 
# function other.  If you enter anything else, you get a reference to the function fail.

# Now, you would normally write "test()" if you wanted to execute test.  Well the 
# parenthesis are just calling the function.  You now have a reference to some function
# so to call it, you have the parenthesis on the end.
funcs.get(target, fail)()

# The above line could be written like this instead
function_to_call = funcs.get(target, fail)
function_to_call()

如果要使用输入,必须将raw_input()的值赋给变量之类的对象。

然后记住,在调用def之前,def(缩进部分)中的所有内容都不会执行。这可能就是为什么什么都不起作用,你不打电话给def。

只要把test()放在某个地方调用它,它就会打印出来。

函数只有在你调用它时才会运行。调用时执行的代码是“def”下的缩进部分。您可以将代码片段放入可能多次调用的函数中,而不必每次都重新编写它。

您需要将原始输入()的输出分配给类似这样的对象(documentation):

s = raw_input('--> ')

你的代码也能工作(太棒了吧?)你刚刚定义了一个函数,但没有调用它。将此项添加到Python文件的末尾(一直到左边,没有缩进):

test()

相关问题 更多 >