The if and else Statements
A program needs the conditional statement to make decisions. We study comparison operators, if, else, elif and logical operators, and write programs that work with age and scores.
All topics (3 of 11)
Chapter 1. Python Basics
Chapter 2. Lists and Strings
Chapter 3. Functions and Modules
Chapter 4. Working with Files
Programs often have to behave differently depending on the situation. The conditional statement if is used for this: if the condition is true, certain commands are executed. A condition is the result of a comparison, and it takes the value True or False.
The comparison operators are == (equal), != (not equal), <, >, <= and >=. Notice that a single = is used to assign a value, while a double == is used to check equality. Several conditions can be combined with the words and, or and not.
First we enter the age: age = int(input("Yoshingiz: ")). Then the first line is if age >= 18: and the second line, indented by 4 spaces, is print("Siz kattasiz") (Uzbek for “You are an adult”). The indentation after the colon is very important in Python: it shows which commands belong to the condition.
If the condition is false, the indented lines are skipped. The action for a false condition uses else: you write the line else: and under it, again indented, for example print("Siz hali kichiksiz"). If there are several cases, elif (“else if”) is added: a grading program has the parts if, elif and else one after another. Python checks the conditions from top to bottom, runs the first true part and skips the rest.
Key takeaways
ifruns commands when the condition is true, andelsegives the path for a false condition.- A condition is a comparison that gives
TrueorFalse. =assigns a value, while==checks equality.- Commands that belong to a condition are written with an indent (4 spaces).
elifchecks several cases in turn;and,orandnotcombine conditions.
Practice tasks
- Write a program that asks for the age and prints “Siz kattasiz” if it is 18 or more, and “Siz hali kichiksiz” otherwise.
- Write a program that decides whether an entered number is even or odd: the condition
n % 2 == 0means the number is even. - A score (from 0 to 100) is entered: using
if,elifandelse, write a program that prints “excellent” for 90 and above, “good” for 70 and above, and “satisfactory” otherwise.
Review questions
Test yourself: think first, then reveal the answer.
1How do the signs = and == differ?Show answerHide answer
= assigns a value to a variable, while == checks whether two values are equal.2What is elif for?Show answerHide answer
To check several conditions in turn: the first true part is executed.3What shows which commands belong to a condition in Python?Show answerHide answer
The indentation (4 spaces) of the lines after the colon.
0 of 11 topics completed
Sign in to mark