In daily programming, we often need to let the program perform different operations based on different situations. For example: deciding whether to bring an umbrella based on the weather, categorizing grades based on scores, or displaying different content based on user permissions. All of these require the use of conditional statements.
Today, I will guide you to fully master the conditional statement techniques in Python, allowing your program to truly “learn” to think!
1. The Importance of Conditional Statements
Programs need to handle various situations. For instance, when a user logs in, it is necessary to check whether the username and password are correct; after calculating the BMI index, it is necessary to determine the health status; when setting a password, it is necessary to check if the password strength is sufficient.
Without conditional statements, programs can only mechanically execute the same operations and cannot flexibly respond to diverse scenarios. Mastering conditional statements is a key step in programming and the foundation for writing practical programs.
2. Single Branch if Statement: The Simplest Prerequisite
The single branch if statement is the simplest form of conditional judgment, and its syntax structure is as follows:
if condition: Code to execute if the condition is true
Notes:
-
If the condition is true, the code to execute must be indented (4 spaces)
-
The code below the if statement will only execute if the condition is true; otherwise, it will not execute.
-
If there is code at the same level as the if statement, that code will execute regardless of whether the condition is true or not.
Practical Case Sharing
Case 1: Age Verification for Driver’s License Application# If an adult, can apply for a driver’s licenseage = int(input(‘Please enter your age: ‘))if age >= 18: print(‘You are an adult and can apply for a driver’s license’)print(‘Today is Saturday, I really want to go out and play’) # This line of code will always executeIn this example, only if the age is greater than or equal to 18 will the message “You are an adult and can apply for a driver’s license” be printed. Regardless of age, the last line of code will always execute.Case 2: Weather Reminder System# Weather reminder, if it rains, remind to bring an umbrellaweather = input(‘Please enter today’s weather: ‘)# Determine the weatherif weather == ‘rain’: print(‘Remember to bring an umbrella when going out~’)Case 3: Password Strength Detection# Determine password strength, length must be greater than 8 characterspassword = input(‘Please enter your password’) # strif len(password) > 8: print(‘Password length is sufficient!’)
3. Double Branch if-else Statement: Either This or That Choice
When we need to handle two possible situations, a single branch if statement is not enough. In this case, we need to use the if-else statement:
if condition: Code to execute if the condition is trueelse: Code to execute if the condition is falseif and else are a whole, only one branch will execute code.
Practical Case Sharing
Case 1: Determine Odd or Even Number
# Determine the odd or even nature of a numbernum = int(input(‘Please enter an integer’))if num % 2 == 0: print(f’{num} is even’)else: print(f'{num} is odd’)In programming, determining odd or even numbers or multiples is usually achieved through modulus operation. A number is even if it is divisible by 2, otherwise it is odd.
Case 2: User Permission Verification
# Login verification, check if the current user is admin (administrator)username = input(‘Please enter your username’)if username == ‘admin’: print(‘Welcome back, dear administrator~’)else: print(‘Ordinary users do not have access rights!’)
4. Multi-Branch if-elif-else Statement: Handling Multiple Situations
When we need to handle more than two possible situations, we need to use multi-branch conditional judgment:
if condition1: Code to execute if condition 1 is true1 is trueelif condition2: Code to execute if condition 2 is true2 is trueelif condition3: Code to execute if condition 3 is true …3 is trueelse: Execute here if none of the above conditions are trueMulti-branch is a whole; as long as one of the conditions in between is true, the conditions below it will not be executed..
Practical Case Sharing
Case 1: Membership Level System
# Determine membership levelpoints = int(input(‘Enter current membership points: ‘))if points > 10000: print(‘Diamond Member’)elif 10000 >= points > 5000: print(‘Platinum Member’)elif 5000 >= points > 2000: print(‘Gold Member’)else: print(‘Ordinary Member’)Case 2: BMI Health Index Calculation# Calculate BMI index and determine health statusheight = float(input(‘Please enter your height (m): ‘)) weight = float(input(‘Please enter your weight (kg)’))# Calculate BMIbmi = weight / (height ** 2)# Determine health statusif bmi < 18.5: print(‘Underweight’, bmi)elif 18.5 <= bmi < 24: print(‘Normal range’, bmi)elif 24 <= bmi < 28: print(‘Overweight’, bmi)else: print(‘Obese’, bmi)
5. Practical Skills for Conditional Judgments
1. Conditional Expression Techniques
Conditions in Python can be various expressions:
-
Comparison Operations:
<span>==</span>,<span>!=</span>,<span>></span>,<span><</span>,<span>>=</span>,<span><=</span> -
Logical Operations:
<span>and</span>,<span>or</span>,<span>not</span> -
Membership Operations:
<span>in</span>,<span>not in</span>
# Complex Condition Exampleage = 20is_student = Trueif age >= 18 and is_student: print(“You are an adult student and can enjoy student discounts”)
2. Nested Conditional Judgments
In some complex cases, we may need to nest another conditional judgment inside a conditional judgment:
# Nested Conditional Judgment Exampleweather = input(“Please enter the weather condition: “) temperature = int(input(“Please enter the temperature: “))if weather == “Sunny”: if temperature > 30: print(“It’s hot, it’s recommended to wear short sleeves and use sunscreen”) else: print(“The weather is comfortable, suitable for outdoor activities”)else: print(“It might rain, please bring an umbrella”)
3. Simplifying Conditional Expressions
For simple conditional assignments, you can use the ternary operator to simplify the code:
# Regular Conditional Judgmentage = 18if age >= 18: status = “Adult”else: status = “Minor”# Simplified Ternary Operatorstatus = “Adult”if age >= 18else“Minor”
6. Common Issues and Debugging Techniques
1. Indentation Errors
Python uses indentation to identify code blocks, common indentation errors include:
-
Mixing spaces and tabs
-
Inconsistent indentation levels
-
Unnecessary indentation
Solution: Use 4 spaces consistently for indentation.
2. Logical Errors
Logical errors in conditional expressions may lead to unexpected results:
# Problematic Conditional Judgmentscore = 85if score > 60: print(“Pass”)elif score > 80: # This condition will never be executedprint(“Good”)Solution: Carefully check the order and logical relationships of the conditions.
3. Floating Point Comparison Issues
Floating point calculations may have precision issues, and direct comparisons should be avoided:
# Not Recommended Floating Point Comparisonresult = 0.1 + 0.2if result == 0.3: # This may not be True print(“Equal”)# Recommended Floating Point Comparison Methodif abs(result – 0.3) < 1e-10: # Use a very small error range print(“Equal”)
7. Summary and Advanced Learning
Conditional statements are a fundamental and core concept in programming. Once mastered, your program will have “decision-making” capabilities. This article introduced:
-
Single Branch if Statement: Handling single condition situations
-
Double Branch if-else Statement: Handling either-or situations
-
Multi-Branch if-elif-else Statement: Handling multiple possible situations
Advanced Learning Suggestions:
-
Learn Boolean logic and truth tables to deeply understand the essence of conditional statements
-
Master short-circuit evaluation characteristics to write more efficient conditional expressions
-
Learn about the strategy pattern in design patterns to understand more complex branching handling methods
Remember, programming is a highly practical skill, writing code frequently is the best way to improve. Try writing various small programs that require conditional statements, such as calculators, grading systems, simple games, etc., to gradually enhance your programming skills.
Thought Question: If you need to design a traffic light control system, how would you use conditional statements to handle the vehicle and pedestrian rules under different traffic light states? Feel free to share your thoughts in the comments!