Decisions with if, else and elif
This is a free course. Log in to run the code exercises and track your progress.
Decisions with if, else and elif
A program often has to choose between actions. This is the diamond of a flowchart. In Python the choice is written with if. The statements that belong to it are indented (4 spaces); indentation is how Python knows where a block starts and ends.
n = int(input())
if n % 2 == 0:
print("Even")
else:
print("Odd")
Use elif ("else if") to check several conditions in order. Python runs the block of the first condition that is True and skips the rest.
percent = 82
if percent >= 90:
grade = "A1"
elif percent >= 75:
grade = "A2"
elif percent >= 33:
grade = "Pass"
else:
grade = "Needs improvement"
print(grade) # A2
Do not forget the colon : at the end of every if, elif and else line.
Read an integer and print Positive, Negative or Zero.
n = int(input())
if n > 0:
print("Positive")
# add an elif for negative numbers and an else for zeroLog in to edit and run this code.