Informatics Practices · Ch 3 — Brief Overview of Python
if..else Statements
if..else Statements
Ordinarily the statements of a program execute one after another, top to bottom. But real problems often present a choice: depending on the outcome of some condition, the program should do one thing rather than another. Python expresses such choices with if..else conditional statements, which let a program perform different tasks or take different paths based on whether conditions turn out true or false.
There are three ways to write if..else statements.
1. The plain if statement
The if statement executes the statement(s) inside it only when its condition is true; when the condition is false, those statements are simply skipped.
age = int(input("Enter your age "))
if age >= 18: # use ':' to indicate end of condition
print("Eligible to vote")
The colon marks the end of the condition. If the user enters 18 or more, the message is printed; otherwise nothing happens.
2. The if...else statement
Here both outcomes get a path: the statement(s) inside if execute when the condition is true, otherwise the statement(s) inside else execute (when the condition is false).
#Program to subtract smaller number from the
#larger number and display the difference.
num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number: "))
if num1 > num2:
diff = num1 - num2
else:
diff = num2 - num1
print("The difference of",num1,"and",num2,"is",diff)
Output:
Enter first number: 5
Enter second number: 6
The difference of 5 and 6 is 1
Because 5 is not greater than 6, the condition is false, so the else branch computes 6 minus 5.
3. The if...elif...else statement
When more than two possibilities exist, if...elif...else checks multiple conditions and executes statements accordingly. elif means else if — and for more clarity one may even write elseif in place of elif.
number = int(input("Enter a number: "))
if number > 0:
print("Number is positive")
elif number < 0:
print("Number is negative")
else:
print("Number is zero")
The number of elif clauses depends on the number of conditions to be checked.
How the interpreter chooses a block
When a conditional statement is reached, the Python interpreter executes the code inside exactly one block — the one selected by the conditions. If the first condition is false, the next condition is checked, and so on down the ladder. The moment one condition turns out true, its corresponding indented block executes and the whole if statement terminates — later conditions are never examined. After that, the statements outside the if..else execute, or the program ends if there are none.