Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

If statement for strings in python? [duplicate]

I am a total beginner and have been looking at http://en.wikibooks.org/wiki/Python_Programming/Conditional_Statements but I can not understand the problem here. It is pretty simple, if the user enters y it should print this will do the calculation although I get a syntax error on IF answer=="y"

answer = str(input("Is the information correct? Enter Y for yes or N for no")) proceed="y" or "Y"  If answer==proceed: print("this will do the calculation"): else: exit() 
like image 335
user829084 Avatar asked Jul 20 '11 13:07

user829084


People also ask

Can you use if statements with strings Python?

We can perform string comparisons using the if statement. We can use relational operators with the strings to perform basic comparisons.

How do you compare strings in IF statements in Python?

Using the == (equal to) operator for comparing two strings If you simply require comparing the values of two variables then you may use the '==' operator. If strings are same, it evaluates as True, otherwise False.

Can we use string in if statement?

The if string rule is used to compare two constant dates which cannot be changed, and it will give the result if the condition is true. The example for the if string statement code is given below.

Can you use if statement twice Python?

Answer 514a8bea4a9e0e2522000cf1 You can use multiple else if but each of them must have opening and closing curly braces {} . You can replace if with switch statement which is simpler but only for comparing same variable.


1 Answers

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") 
like image 62
Daniel DiPaolo Avatar answered Oct 09 '22 02:10

Daniel DiPaolo