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

标签 python function raw-input

我是 python 的新手,我正在尝试为具有 raw_input 和函数的程序创建一个类似命令的东西。由于某种原因,它一直没有工作。这是我一直在测试的代码:

raw_input()

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

最佳答案

raw_input 将阻塞,直到您输入内容。当收到换行符(用户按回车键)时,该值将被返回并可以存储。您似乎从未尝试调用您的函数 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()

关于python - 尝试将原始输入与函数一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16327238/

相关文章:

python - Django Group 权限如何在模板中打印

php - 为什么在函数内部使用 "global"引用被认为是不好的做法?

javascript - Javascript 函数中的对象

python - 如何使用 Tkinter Entry 像 raw_input

python xlsxwriter 缺少图表

python - 如何生成二维 numpy 数组?

javascript - 这在 JavaScript 函数中指的是什么?

python - 当用户决定是否在 raw_input 中写入任何内容时如何做其他事情?

python - 使用 pyparsing 解析键值对,其中值可能会持续多行