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
An example of a small test
For example, to send a bar mitzvah notification to someone over 18:
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
Practical examples
Change the coming-of-age ceremony example into a box office query scenario:
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
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:
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!
**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:
None、False*Number zero:0、0.0、0j - 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:
Check if the inventory is empty:
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:
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
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.
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:
(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:
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:
if、elif、elsemust be followed by a colon, which is a mandatory requirement of Python syntax!
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.
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.
8.4 Not processedinput()type conversion
input()What is returned is a string and cannot be directly compared with an integer.
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.
Summarize
Python's conditional judgment is the core of controlling program flow. Today we have sorted out:
- Basic single branch
if, double branchif-else, multiple branchesif-elif-else - Use "True/False" to simplify code
- Handle user input securely
- Small case combined with BMI calculator
- Modern Python’s type annotations, walrus operators, and pattern matching
- 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 ~

