If Statement, it is also known as a condition statement. If Statement increases the functionality of a Python. The ability to use logic “if-then-else” in your program is one of the most fundamental aspects of programming. Python programming provides an easy way to tell your program what to do if something is true, and what to do if something is false.
1. Determine what conditions you want to test. Here we see some example of the use of the if statement. The first section defines two variables (a and b) to use with if statement. Then we use two statements to compare the two variables to see if one is bigger than the other.
2. Determine which events you want to occur if the statement is true.
3. Create an if statement using a test condition, and place the events that occur if the statement is true immediately after the if statement. Use a colon (:) to indicate the end of the if statement: if a<b print “a is small than b”.
Example Greatest Between Two Variables
a = 5 b = 6 if a < b: print ("a is small than b") elif a > b: print("b is greater than a") else: print("Both are same")
4. Think about; if you have more than one condition, that’s you want to test.
5. if you have more than one condition, you can use “else-if” to continue your if statement. In Python, the keyword “elif” is used as shorthand for “else-if”. The elif statement ends with a colon (:) elif a>b print “b is greater than a”.
6. You can use as many as “elif”, one after another, as you needed to satisfy your needs.
7. If all the sequence of events that you want to occur are false. Then if statement end with else statement with a colon (:) print “Both are same”.
8. The next we check if two items are equal or not. The operator for testing equality is == and the operator to test inequality is! =. Here are the examples.
Example if statements: equal or not equal
if a == b: print("a is equal to b") if a != b: print("a not equal to b")
Note: It is straightforward to know when to use == and =. We use == if something is equal, we use = if something is same, i.e., to assign a value to something.
9. Each IF statement can check multiple conditions with and/or. They are also called operators such as + or -.
Example if statements, using “and” and “or”
if a < b and a < c: print("a is less than b and c") if a < b or a < c: print("a is less than b or c (or both)")
10. Python supports Boolean variables, but what are Boolean variables? Boolean variables can store True (True) or False value (False). A statement if it needs a true expression (True) or False (False) to be evaluated. Here are the examples.
IF Statement and Boolean types # Boolean Data type. a = True if a: print ("a is true") Example operator not (No) # How to use the not operator if not (a): print ("A is false")