Often in programming there is a need to make decisions. Decisions are made according to some conditions.
Decisions can be made using if conditions.
Syntax for using if:
if condition: #your block of code #do this #and this
Here block of code means the code that is going to get executed when the condition inside the if block returns true.
Block of code is a set of statements and is created by providing 4 times spaces or a single tab.
After putting colon and hitting enter, Python IDLE automatically creates a block.
if 5>4: print("5 is greater than 4") print("Bye")
5 is greater than 4
Sometimes situation arises when we have to perform couple of instructions if the condition inside if statement goes false. In that case we use else.
else is always followed by if and can't be used alone.
Syntax for using else:
if condition: #do this else: #do something else
if 5>6: print("5 is greater than 6") else: print("6 is greater than 5")
6 is greater than 5
What if there are more if conditions than just one. For example, if it rains then I'll take umbrella, if its sunny then I'll get my goggles, if neither of them then I'll just leave without taking anything among them.
In such situations, elif comes in handy.
Syntax for using elif
if condition1: #do this elif condition2: #do this else #do something else
You can use any number of elif. elif is always followed by if.
Example: Copy and paste the following code by creating a new file and saving it as 'condition.py'.
color = 'red' if color=='blue': print('color is blue') elif color=='red': print('color is red') elif color=='green': print('color is green') else: print('color is black')
color is red