The if…else statement
The if…else statement in Python is used when you need to choose between two alternatives. The else clause in the code will be executed if the condition for the if statement isn’t met, which allows you to perform an alternative task. The syntax of the if…else statement is:
if condition: statements else: statements
Consider the following example:
name = input('What is your name? ') x = int(input('How old are you? ')) if x >= 21: print(name,'you are old enough.') else: print(name,'you are not old enough.')
Here is what happens if we enter the values Mark and 19:
What is your name? Mark How old are you? 19 Mark you are not old enough.
In the example above the user is prompted to enter his name and age. The if statement will than evaluate whether the user if 21 or older and print the corresponding message. If the user enter a number less than 21, the else statement will be executed and the corresponding message will be printed. Note that the else statement will be executed only if the if statement evaluates to false. If the user enters a number greater or equal to 21, the code under the else statement will not be executed.
Here is another example:
x = int(input('Enter a number: ')) if x % 2 == 0: # checks whether the number is divisible by 2. print('The number you have entered is an even number.') else: print('The number you have entered is an odd number.')
Enter a number: 5 The number you have entered is an odd number. >>> Enter a number: 67 The number you have entered is an odd number. >>> Enter a number: 100 The number you have entered is an even number.