试图将使用中的变量更改为用户输入的内容
问题描述:
我还没有找到满足我的需求的答案,或者足够简单,因此我实际上可以理解,因为我是相对较新的python!试图将使用中的变量更改为用户输入的内容
我有一个变量标记为难度,要求用户输入一个字符串来表明他们是否想要简单的中等或硬模式。不幸的是,我无法成功地让python检查所用单词的输入,并给他们我想要的东西,最后我以“易于未定义”或“中等未定义”或“难以定义”结束。有没有办法让我解决这个问题?这里是一个问题被封闭,以我的一小段代码:
difficulty=input("What difficulty do you wish to choose, easy,medium or hard?")
if difficulty==easy:
print("You have chosen the easy mode, your test will now begin")
print("")
elif difficulty==medium:
print("You have chosen the medium mode, your test will now begin")
else:
print("You have chosen the hard mode or tried to be funny, your test
will now begin")
答
首先,修正你的缩进(如果它只是在你的例子中不是问题)。其次,你需要把简单,中等和硬盘在单'
或双引号"
:
difficulty=input("What difficulty do you wish to choose, easy,medium or hard?")
if difficulty=="easy":
print("You have chosen the easy mode, your test will now begin")
print("")
elif difficulty=="medium":
print("You have chosen the medium mode, your test will now begin")
else:
print("You have chosen the hard mode or tried to be funny, your test
will now begin")
如果你不把它们放在引号,那么你是不是比较difficulty
这个词容易,而是涉及名为easy
的变量。这当然会导致错误,因为不存在这样的变量。然而引号告诉python将简单解释为一个字符串。
答
您正在尝试从用户那里获取一个字符串(input
将返回一个字符串),那么在这种情况下,把它比作另一个字符串'easy'
或'medium'
。 Here is a link to一个谷歌开发文章,谈论你可以对python中的字符串做一些基本的事情。
difficulty = input("What difficulty do you wish to choose, easy,medium or hard?")
if difficulty == 'easy':
print("You have chosen the easy mode, your test will now begin")
print("")
elif difficulty == 'medium':
print("You have chosen the medium mode, your test will now begin")
else:
print("You have chosen the hard mode or tried to be funny, your test will now begin")
当你把easy
或medium
在你的代码,你告诉蟒蛇,他们是变量(link to python variable tutorial)不是字符串。在这种情况下,您尚未定义easy
变量,即:easy = 'some data'
。因为你还没有定义它,python不知道该怎么做easy
它会抛出一个错误。
您必须将输入与一个字符串进行比较:'if difficult ==“easy”:' – Prune
'难度==“简单”'。这里需要字符串文字。 –
@Jan'raw_input'已从版本3的python中删除。 –