简体   繁体   English

如何使用字符串执行布尔if语句?

[英]How to do a Boolean if statement with strings?

I have a chunk of code that goes like: 我有一段代码如下:

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

It gives the following error: 它给出以下错误:

NameError: name 'Yes' is not defined

How do I fix this? 我该如何解决?

Assuming this is python, use raw_input instead of input. 假设这是python,请使用raw_input代替输入。 Input is considered dangerous, because it evaluates whatever you input, so if you do: 输入被认为是危险的,因为它会评估您输入的任何内容,因此如果这样做:

   x = input()

and enter 2+4, x will be equal to 6. raw_input just gives you the entered string. 并输入2 + 4,x等于6。raw_input仅提供输入的字符串。

Use raw_input() instead of input() : 使用raw_input()代替input()

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

Think of input() as if you was to type directly into the interpreter, so yes would need to be 'yes' for python to known you mean the string yes . 想想input()就像您要直接在解释器中键入一样,因此对于python来说, yes必须为'yes' ,才能知道您的意思是字符串yes

Edit: 编辑:

You need to use while to loop. 您需要使用while循环。

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

print 'Correct'

print 'Doing something else...'

#Carry on here 

Output: 输出:

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

This version will accept any variation of "Yes", so "yes", "YES", "YeS", "yES", etc. 此版本将接受“是”的任何变体,因此“是”,“是”,“是”,“是”等。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM