title: Conditional judgment description: Python uses the if statement for conditional judgment. The basic syntax is as follows:

#Conditional judgment

Friends who have just started learning programming will definitely be curious: Can the program only go from top to bottom to the bottom? Can the user decide whether to allow access based on the different passwords entered by the user? Or give different movie rating tips based on age? At this time, it is the core of Control Flow - Conditional Judgment.

Python's conditional judgment syntax is very friendly: there are no redundant braces, only indentations are used to express attribution relationships, and it reads like natural language. Today we will learn all this knowledge at once from entry level to advanced level!


1. The most basic single branch:ifstatement

When you only need to perform a specific operation when a certain condition is met, use a single branchifThat's enough.

Grammar structure

if 能判断真假的条件:
    # 条件为 True 时执行的代码块(必须缩进,推荐 4 个空格)

An example of a small test

For example, to send a bar mitzvah notification to someone over 18:

age = 20
if age >= 18:
    print('🎉 恭喜你成年啦!')
    print('记得办理身份证更新哦~')

Here'sage >= 18is a Boolean expression, the result can only beTrueorFalse
if forTrue, execute the two lines of code indented below; ifFalse, these two lines will be skipped directly.


2. If the condition is true, do A, if the condition is false, do B:if-elsedouble branch

A single branch can only handle "do/don't do", but many times we need a required branch to choose one of the two. For example: If you are old enough, buy an adult ticket, if you are not old enough, buy a child ticket. At this time addelseThat’s it.

Grammar structure

if 条件:
    # 条件为 True 时执行
else:
    # 条件为 False 时执行

Practical examples

Change the coming-of-age ceremony example into a box office query scenario:

age = 7
if age >= 18:
    print('请购买普通票:50元')
else:
    print('请购买儿童票:25元')

3. Choose one of three or four? useif-elif-elsemultiple branches

If there are more than two conditions, and they are mutually exclusive and consecutive (for example, movie rating: 0‑3 free ticket, 4‑12 half ticket, 13‑64 full ticket, 65+ free ticket), do not write nested onesif-else. If you nest too much, readability will drop sharply. Python provides a dedicatedelif(Right nowelse ifabbreviation).

Grammar structure

if 条件1:
    # 条件1真,执行这里,后面全部跳过
elif 条件2:
    # 条件1假、条件2真,执行这里
elif 条件3:
    # 前两个假、第三个真,执行这里
else:
    # 前面所有条件都不满足时的兜底逻辑

Pay attention to the execution order!

This is the easiest pitfall for novices: **Python will match the conditions from top to bottom. Once it encounters the firstTrueConditions, after executing the corresponding code block, the remainingelifandelseThey will be skipped directly and not checked again. **

Let’s look at an example of correct movie rating:

age = 25
if age >= 65:
    print('请出示老年证免票')
elif age >= 13:
    print('请购买全票:50元')   # 25 岁匹配这里
elif age >= 4:
    print('请购买半票:25元')
else:
    print('请家长陪同免票')

If you accidentally put a condition with a large range (such asage >= 4) written in front, the 25-year-old will also be misjudged as a half-vote!

# 错误顺序示例
if age >= 4:          # 25 也满足
    print('半票')     # 这里会被执行,后面的全跳过
elif age >= 13:
    print('全票')

**So, be sure to put conditions with a smaller scope and stricter restrictions first. **


4. No need to write== True? Python's "True/False" Simplification

Python has a very thoughtful design: **not onlyTrueandFalseTalent is the condition! ** Many values ​​are automatically treated asFalse(false value), everything else is treated asTrue(True value), can be directly used to simplify conditional judgment.

Automatically regarded asFalsevalue

A few of the most common ones to remember are:

  • Explicit false:NoneFalse *Number zero:00.00j
  • Empty sequence:''(empty string),[](empty list),()(empty tuple),set()(empty collection)
  • Empty mapping:{}(empty dictionary)

Simplified before and after comparison

Check if the user entered valid content:

# 冗余写法
username = input('请输入用户名:')
if username != '' and username is not None:
    print('用户名有效')

# Pythonic 写法
if username:
    print('用户名有效')

Check if the inventory is empty:

# 冗余写法
count = 0
if count == 0:
    print('库存为空')

# 简化写法
if not count:
    print('库存为空')

5. Be careful when handling user input! Type conversion + exception catching cannot be missing

input()The user input obtained by the function must be a string. If you want to use it for numerical comparison (age, height, weight, etc.), ** must first be converted tointorfloat**。

However, there is a hidden danger in direct conversion: if the user inputs something other than a pure number (such as "abc"), the program will directly exit with an error. To make the program more robust, remember to addtry-exceptCatch exceptions.

Safe and complete input processing example

Determine whether the user is before 00 or after 00:

try:
    birth_year = int(input('请输入你的出生年份(四位数字):'))
    if birth_year < 2000:
        print('你是 00 前的朋友~')
    else:
        print('你是 00 后的新生代呀!')
except ValueError:
    print('❌ 输入无效,请输入纯数字的四位年份!')

6. Practical case: BMI calculator

BMI (Body Mass Index) is a commonly used indicator to measure whether your weight is healthy, and it is just suitable for practicing using multi-branch conditional judgment.

Complete code

def calculate_bmi(height: float, weight: float) -> str:
    # 计算 BMI
    bmi = weight / (height ** 2)
    bmi_display = round(bmi, 2)

    # 多分支判断 BMI 区间
    if bmi < 18.5:
        status = '体重过轻'
    elif 18.5 <= bmi < 25:
        status = '体重正常(继续保持!)'
    elif 25 <= bmi < 28:
        status = '体重过重'
    elif 28 <= bmi < 32:
        status = '轻度肥胖'
    else:
        status = '重度肥胖(建议咨询医生哦~)'

    return f'你的 BMI 是 {bmi_display},状态:{status}'

# 测试一下
if __name__ == '__main__':
    try:
        user_height = float(input('请输入你的身高(单位:米,如 1.75):'))
        user_weight = float(input('请输入你的体重(单位:千克,如 70):'))
        print(calculate_bmi(user_height, user_weight))
    except ValueError:
        print('❌ 请输入有效的数字!')

7. Advanced writing methods of modern Python (3.6+)

If your Python version is relatively new (at least 3.8 is recommended, the latest stable version is 3.13), you can use these features to make the code more concise and Pythonic.

7.1 Type annotations (3.6+)

Although Python is a dynamically typed language, adding type annotations can make the code more readable and make it easier for editors and static checking tools (such as mypy and Pyright) to detect problems in advance.

def check_age(age: int) -> str:
    if age >= 18:
        return '成年人'
    return '未成年人'

7.2 Walrus operator:=(3.8+)

The walrus operator can complete "assignment + judgment" simultaneously in conditional judgment, reducing duplicate code. The previous example of judging before 00 / after 00 can be simplified to this:

try:
    if (birth_year := int(input('请输入出生年份:'))) < 2000:
        print('00 前')
    else:
        print('00 后')
except ValueError:
    print('无效输入')

(birth_year := int(...))First convert the input into an integer and assign it tobirth_year, and use this value as a comparison condition to kill two birds with one stone!

7.3 Pattern matchingmatch-case(3.10+)

Pattern matching is a major feature introduced in Python 3.10. In basic scenarios andif-elif-elseAlmost the same, but it will be very useful when dealing with complex structures (such as lists, dictionaries, class instances). Let’s first look at a comparison of age judgment:

# if-elif-else 写法
if age >= 18:
    print('成年人')
elif age >= 13:
    print('青少年')
else:
    print('儿童')

# match-case 写法
match age:
    case age if age >= 18:
        print('成年人')
    case age if age >= 13:
        print('青少年')
    case _:
        print('儿童')

Here's_is a wildcard, equivalent toelseThe bottom-up logic.


8. 5 common mistakes that novices must make

8.1 Forgot to write the colon:

ifelifelsemust be followed by a colon, which is a mandatory requirement of Python syntax!

# 错误
if age >= 18
    print('成年')

# 正确
if age >= 18:
    print('成年')

8.2 Indentation confusion

Python uses indentation to indicate where code blocks belong. Inconsistent indentation (for example, some use 2 spaces, and some use 4), or indentation in places that should not be indented will lead to syntax errors.

# 错误 1:缩进格数不一致
if age >= 18:
  print('成年')
    print('更新身份证')   # 多了 2 个空格,报错

# 错误 2:不该缩进的写成了缩进
if age >= 18:
    print('成年')
    print('更新身份证')
  print('欢迎光临')      # 这行缩进了,但它不在 if 块内,报错

# 正确(统一 4 空格,块内缩进,块外顶格)
if age >= 18:
    print('成年')
    print('更新身份证')
print('欢迎光临')

8.3 Confused assignment=and equality judgment==

=It is an assignment,==It is to determine whether they are equal. This is a stupid mistake that almost all novices make.

# 错误
if age = 18:   # 赋值不能作为条件,会报错
    print('刚好成年')

# 正确
if age == 18:
    print('刚好成年')

8.4 Not processedinput()type conversion

input()What is returned is a string and cannot be directly compared with an integer.

# 错误
age = input('请输入年龄:')
if age >= 18:   # 字符串和整数比较,报错
    print('成年')

# 正确(加入 int 转换和异常捕获)
try:
    age = int(input('请输入年龄:'))
    if age >= 18:
        print('成年')
except ValueError:
    print('无效输入')

8.5 Wrong condition judgment order

As mentioned before, smaller scope and more stringent conditions must be written in front, otherwise the subsequent branches will never be executed.

# 错误顺序
age = 25
if age >= 4:       # 25 也满足,输出「半票」,后面全跳过
    print('半票')
elif age >= 13:
    print('全票')

# 正确顺序
if age >= 65:
    print('免票')
elif age >= 13:
    print('全票')
elif age >= 4:
    print('半票')
else:
    print('免票')

Summarize

Python's conditional judgment is the core of controlling program flow. Today we have sorted out:

  1. Basic single branchif, double branchif-else, multiple branchesif-elif-else
  2. Use "True/False" to simplify code
  3. Handle user input securely
  4. Small case combined with BMI calculator
  5. Modern Python’s type annotations, walrus operators, and pattern matching
  6. 5 pitfalls that novices must step into

By using these syntaxes appropriately, you can already write programs with "selection capabilities"! In the next article, we will learn about loops and let the program have "repeated execution capabilities", so stay tuned ~