如何用字符串做一个布尔if语句?

时间:2012-10-28 21:27:39

标签: python if-statement boolean nameerror

我有一大堆代码如下:

maybeYes = input("Please enter Yes to start.")
if maybeYes == "Yes":
    pass
else:
    print "Wrong answer."

它出现以下错误:

NameError: name 'Yes' is not defined

我该如何解决这个问题?

3 个答案:

答案 0 :(得分:1)

假设这是python,请使用raw_input而不是input。 输入被认为是危险的,因为它会评估您输入的内容,因此如果您这样做:

   x = input()

并输入2 + 4,x将等于6. raw_input只输给你输入的字符串。

答案 1 :(得分:1)

使用raw_input()代替input()

>>> maybeYes = raw_input("Please enter Yes to start ")
Please enter Yes to start yes
>>> maybeYes
'yes'

input()视为直接输入解释器,因此yes需要'yes'才能知道python是yes

修改

您需要使用while来循环播放。

while raw_input("Please enter Yes to start: ") != 'Yes':
       print 'Wrong'

print 'Correct'

print 'Doing something else...'

#Carry on here 

输出:

Please enter Yes to start: nowg
Wrong
Please enter Yes to start: wggwe
Wrong
Please enter Yes to start: Yes
Correct
Doing something else...

答案 2 :(得分:0)

此版本将接受“是”的任何变体,因此“是”,“是”,“是的”,“是”等等。

answer = raw_input('Please enter Yes to start: ')
while answer.upper() != 'YES':
   print 'Sorry, your entered something else'
   answer = raw_input('Please enter Yes to start: ')
print "Thank you, you entered ", answer