Appearance
Conditional Judgments
Computers can automate many tasks because they can perform conditional judgments.
For example, to print different content based on a user's age input, you can use the if
statement in Python:
python
age = 20
if age >= 18:
print('your age is', age)
print('adult')
According to Python's indentation rules, if the if
statement evaluates to True
, the indented print
statements will be executed. Otherwise, nothing happens.
You can also add an else
statement to the if
statement, which means that if the if
condition is False
, the content inside the else
block will be executed:
python
age = 3
if age >= 18:
print('your age is', age)
print('adult')
else:
print('your age is', age)
print('teenager')
Make sure not to omit the colon :
.
Of course, the above judgment is very rough. You can use elif
for more detailed judgments:
python
age = 3
if age >= 18:
print('adult')
elif age >= 6:
print('teenager')
else:
print('kid')
elif
is short for else if
, and you can have multiple elif
conditions. The complete form of the if
statement is:
python
if <condition1>:
<execute1>
elif <condition2>:
<execute2>
elif <condition3>:
<execute3>
else:
<execute4>
The if
statement is evaluated from top to bottom. If a condition is True
, the corresponding block is executed, and the rest of the elif
and else
blocks are ignored. Please test and explain why the following program prints "teenager":
python
age = 20
if age >= 6:
print('teenager')
elif age >= 18:
print('adult')
else:
print('kid')
The reason is that once the if
condition age >= 6
evaluates to True
, the corresponding block is executed, and the subsequent elif
and else
blocks are ignored.
Simplified Conditionals
The if
condition can be written in a simplified form. For example:
python
if x:
print('True')
As long as x
is a non-zero number, non-empty string, non-empty list, etc., it is evaluated as True
. Otherwise, it is evaluated as False
.
Revisiting input()
Let's look at a problematic conditional judgment. Many students use input()
to read user input, making the program more interactive:
python
birth = input('birth: ')
if birth < 2000:
print('Born before 2000')
else:
print('Born after 2000')
If you enter 1982
, the program raises an error:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unorderable types: str() > int()
This is because input()
returns a str
type, and a string cannot be directly compared with an integer. You must first convert the string to an integer using the int()
function:
python
s = input('birth: ')
birth = int(s)
if birth < 2000:
print('Born before 2000')
else:
print('Born after 2000')
Now, if you run the program again, it will produce the correct result. However, if you enter abc
, you will get another error:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: 'abc'
The int()
function throws a ValueError
when it encounters a string that is not a valid number. The program will then exit.
How do you check and catch runtime errors in a program? This will be covered in error handling and debugging later.
Exercise
Xiao Ming is 1.75 meters tall and weighs 80.5 kg. Please use the BMI formula (weight divided by the square of the height) to calculate his BMI index, and based on the BMI index:
- Less than 18.5: Underweight
- 18.5-25: Normal
- 25-28: Overweight
- 28-32: Obese
- Above 32: Severely obese
Use if-elif
to determine and print the result:
python
height = 1.75
weight = 80.5
bmi = weight / (height ** 2)
if bmi < 18.5:
print('Underweight')
elif bmi < 25:
print('Normal')
elif bmi < 28:
print('Overweight')
elif bmi < 32:
print('Obese')
else:
print('Severely obese')
Summary
Conditional judgments allow the computer to make decisions on its own. Python's if...elif...else
is very flexible.
Conditions are matched from top to bottom, and when a condition is satisfied, the corresponding block of code is executed. Subsequent elif
and else
blocks will not be executed.