简体   繁体   中英

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. 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.

Use raw_input() instead of 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 .

Edit:

You need to use while to loop.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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