In the programs we have seen till now, there has always been a series of statements faithfully executed by Python in exact top-down order. What if you wanted to change the control of the flow of executes? For example, you want the program to take some decisions and do different things depending on different situations, such as printing Good Morning or Good Evening depending on the time of the day?
As you might have guessed, this is achieved using conditional statements. In Python if statements used for the same.
If Statement
The if statement is used to check a condition: if the condition is true, we run a block of statements (called the if-block), else we process another block of statements (called the else-block). The else clause is optional.
Code Segment:
number = 23 if number%2 == 1: # New block starts here print ('Number is Odd.') # The value in number variable is Odd. else: print ('Number is Even') # The value in number variable is Even. print ('Done') # This last statement is always executed, # after the if statement is executed.
Output:
Number is Odd.
Done
Done
Post a Comment