试图评估用户输入并将其用作python中的变量

时间:2012-02-28 22:10:33

标签: python string variables eval user-input

我是python的初学者和任何编码都是这样的,我在编写一些代码时遇到了一些问题:

loop = 0
hellosentence = "You have selected the hello sentence"
questionsentence = "You have selected the question sentence"

usrinput  = raw_input("Which test would you like to bring up? ")

print eval(usrinput)+sentence

end = raw_input("Press any key to quit...")

我正在尝试以此为目的运行代码。

最后有多个带句子的名字。

请求用户想要提出的“句子”

一旦用户输入了句子,它会评估他们输入的内容,说“你好” 并将其与“句子”结合起来,使变量“hellosentence”,从而调出变量的字符串。

我14岁并且真的想学习如何理解这种语言,所以如果有人知道我能做些什么来解决这个错误,我将非常感激。

3 个答案:

答案 0 :(得分:3)

eval将获取您提供的字符串并对其进行评估。在这种情况下,它采用输入的输入字符串。根据您定义的变量判断,您希望获取输入并将sentence附加到其中,因此如果他们键入'hello',您将返回价值hellosentence

解决问题的直接方法是给eval正确的输入:

print eval(usrinput+'sentence')

这可能解决了你的问题,但这不是一个好方法。 eval是工作的错误工具;错误恢复将成为一个问题,如果这是生产代码,那么对于想要将程序变成病毒的人来说,这将是一个很大的漏洞。

正确的工具是字典,您可以使用输入来查找正确的输出。

selection = {'hello': hellosentence, 'question': questionsentence}
print selection[usrinput]

答案 1 :(得分:1)

首先,你的

loop = 0 

线是没有意义的。你可以看到它再也不会被使用了。

print eval(usrinput)+sentence 

我可以看到你想要完成的事情,在变量中打印hellosentence。然而,它不会那样工作。使用eval()并没有为你做任何事情,所以想象一下写

print usrinput+sentence

这不会打印任何变量的值与usrinput和句子结尾具有相同的开头。它将打印usrinput的值,然后打印句子的值。由于您没有句子变量,因为句子的值不存在而导致错误。

假设用户在提示输入时输入“hello”。打印行不会打印hellosentence的值,但会打印“hello”,然后出现错误,因为句子不存在。基本上,你不能把它当作纯英语,因为你可以这样:

pretzel = "apple"
print pretzel

这将打印“apple”而不是“椒盐卷饼”。如果你不明白这一点,我强烈建议你阅读变量和作业。

您必须检查usrinput的值。

if usrinput = "hello":
    print hellosentence

您程序最后一行的结束变量什么都不做,因为您只需将值赋给end。尝试检查end的值,就像我们使用usrinput一样。

您似乎对程序的实际执行方式存在误解。我建议阅读变量和作业。

答案 2 :(得分:0)

这应该完成工作 - 除了eval的不安全部分之外的任何事情;))

input = raw_input # remove this if you already use Python 3...

def my_func():
    for i in range(10):
        pass
    return "How are you today?"

sentences = {}
sentences["hello"] = "Hello world..."
sentences["question"] = my_func

usrinput = input("Which test...?")

try:
    obj = sentences[usrinput]
    if hasattr(obj, '__call__'):
        print(obj())
    else:
        print(obj)
except KeyError:
    print("Invalid input...")
finally:
    input("Press ENTER to quit...")