If statement for strings in python? [duplicate] If statement for strings in python? [duplicate] python python

If statement for strings in python? [duplicate]


Even once you fixed the mis-cased if and improper indentation in your code, it wouldn't work as you probably expected. To check a string against a set of strings, use in. Here's how you'd do it (and note that if is all lowercase and that the code within the if block is indented one level).

One approach:

if answer in ['y', 'Y', 'yes', 'Yes', 'YES']:    print("this will do the calculation")

Another:

if answer.lower() in ['y', 'yes']:    print("this will do the calculation")


If should be if. Your program should look like this:

answer = raw_input("Is the information correct? Enter Y for yes or N for no")if answer.upper() == 'Y':    print("this will do the calculation")else:    exit()

Note also that the indentation is important, because it marks a block in Python.


Python is a case-sensitive language. All Python keywords are lowercase. Use if, not If.

Also, don't put a colon after the call to print(). Also, indent the print() and exit() calls, as Python uses indentation rather than brackets to represent code blocks.

And also, proceed = "y" or "Y" won't do what you want. Use proceed = "y" and if answer.lower() == proceed:, or something similar.

There's also the fact that your program will exit as long as the input value is not the single character "y" or "Y", which contradicts the prompting of "N" for the alternate case. Instead of your else clause there, use elif answer.lower() == info_incorrect:, with info_incorrect = "n" somewhere beforehand. Then just reprompt for the response or something if the input value was something else.


I'd recommend going through the tutorial in the Python documentation if you're having this much trouble the way you're learning now. http://docs.python.org/tutorial/index.html