Computers can perform many automated tasks because they can make conditional judgments on their own.
For example, to input a user’s age and print different content based on that age, you can use an if statement in a Python program:
age = 20
if age >= 18:
print('your age is', age)
print('adult')
According to Python’s indentation rules, if the condition in the if statement evaluates to True, the two indented print statements are executed. Otherwise, nothing is done.
You can also add an else clause to the if statement. This means that if the if condition is False, the code block under if is skipped, and the code block under else is executed instead:
age = 3
if age >= 18:
print('your age is', age)
print('adult')
else:
print('your age is', age)
print('teenager')
Note: Don’t forget to include the colon : at the end of the if and else lines.
Of course, the above judgment is rather simplistic. You can use elif (short for “else if”) for more granular conditions:
age = 3
if age >= 18:
print('adult')
elif age >= 6:
print('teenager')
else:
print('kid')
Since elif is short for “else if”, you can have multiple elif clauses. Therefore, the complete form of an if statement is:
if <condition 1>:
<execute code block 1>
elif <condition 2>:
<execute code block 2>
elif <condition 3>:
<execute code block 3>
else:
<execute code block 4>
A key characteristic of if statement execution is that it evaluates conditions from top to bottom. If a condition evaluates to True, the corresponding code block is executed, and all subsequent elif and else clauses are skipped. Please test the following program and explain why it prints teenager:
age = 20
if age >= 6:
print('teenager')
elif age >= 18:
print('adult')
else:
print('kid')
The condition in an if statement can also be written concisely. For example:
if x:
print('True')
In this case, x is evaluated as True if it is a non-zero number, a non-empty string, a non-empty list, or any other non-empty or non-zero object. Otherwise, it is False.
input()Finally, let’s look at a conditional judgment with a potential issue. Many students use the input() function to read user input, which makes programs more interactive:
birth = input('birth: ')
if birth < 2000:
print('00前') # Born before 2000
else:
print('00后') # Born in or after 2000
If you run this and enter 1982, you’ll get an error:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unorderable types: str() > int()
This error occurs because the input() function always returns a string (str). You cannot directly compare a string with an integer. You must first convert the string to an integer using Python’s int() function:
s = input('birth: ')
birth = int(s)
if birth < 2000:
print('00前')
else:
print('00后')
Now, running the program again will yield the correct result. However, what happens if the user enters abc? You’ll 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 raises a ValueError if the input string is not a valid integer, causing the program to terminate.
How can we check for and handle such runtime errors? We will cover this in a later section on errors and debugging.