For making decisions in python on particular conditions if, elif, else keywords are used.
Python supports the usual comparison operator
- Equals a == b
- Not Equals a != b
- Less than a < b
- Less than or Equal to a <= b
- Greater than a > b
- Greater than or Equal to a >= b
How to use
In python curly braces are not use for writing if or any other block level scope use indentation to write inner code of if. Like after writing if condition there must be an indentation of white spaces in next line it can be any number of spaces from one to onward by one thing is to remember that if you use one space on first line indent than there should also be one space ident in next line on current scope. For exampel
a = 33 b = 200 if b > a: print("b is greater than a")
In this code if statement there are 2 white spaces used for ident of we did not used ident python interpreter will give an error. Now if want to add one more statement in this scope so we will write like this
a = 33 b = 200 if b > a: print("b is greater than a") print("a is less than b")
So here we can see that indentation on 2nd statement is same as previous line. So this is necessary in this scope.
elif keyword is similar to elseif this is used to check if first condition is not true than try this condition if this condition is true than execute this level of code. Example
a = 33 b = 33 if b > a: print("b is greater than a") elif a == b: print("a and b are equal")
The else keyword is used when all above given statements are false.
a = 200 b = 33 if b > a: print("b is greater than a") elif a == b: print("a and b are equal") else: print("a is greater than b")
Nested if is used if you need to check a condition inside another if condition. So for writing nested if we will write if condition inside if block by using single ident of this scope and than add one more ident for inner if condition for example:
x = 41 if x > 10: print("Above ten,") if x > 20: print("and also above 20!") else: print("but not above 20.")
Pass keyword in python
The pass keyword is used if you want to leave inner of if condition empty like its mean do nothing for example
a = 2 if a < 10: pass else: print("a is not less than 10")
So, In this code if a is less than 10 than code will do nothing and if a is equal to or greater than 10 than else statement will work.