Python conditional statement introduction
Conditional statements are the basic control structure in programming, allowing programs to execute different code blocks according to specific conditions. Conditional statements in Python include if, elif (the abbreviation of else if) and else clauses. Conditional statements enable programs to make decisions and perform different operations according to different situations, greatly enhancing the flexibility and intelligence of programs.
When using conditional statements, you need to pay attention to the following points:
- Python uses indentation to identify code blocks to ensure consistent and correct indentation
- A colon must be followed by a conditional expression (:)
- Multiple conditions can be combined using logical operators (and, or, not)
- Complex conditional logic can be used to use nested conditional statements or split into multiple simple conditions
This article mainly introduces the following conditional statements:
- if structure: Execute a specific code block when the condition is true
- if…else structure: Execute different code blocks according to the authenticity of the condition
- if…elif…else structure: Check multiple conditions in order and execute the code block corresponding to the first true condition
- Nested conditional statements: Include other conditional statements inside conditional statements
- Conditional expression (ternary operator): Concisely express conditional logic
if structure
If structure syntax is as follows:
A statement group is a python statement containing one or more statements, followed by a colon: The statements in the statement group must be at the same indentation level.
if Conditional expression: Statement group
If the result of the conditional expression is True, the code in the if statement block is executed; if the result of the conditional expression is False, the if statement block is skipped.
Example
Example 1: Simple if statement
# Check if a number is a positive numbernum = 10 if num > 0: print("This is a positive number")
Running results:
This is a positive number
Example 2: If statement and logical operator
# Check if a person meets the requirements for participating in an eventage = 25 is_student = True if age >= 18 and is_student: print("You meet the conditions for participating in the event")
Running results:
You meet the conditions for participating in the event
if…else structure
The if…else structure allows us to execute another set of statements when the condition is not satisfied. The syntax is as follows:
if Conditional expression: Statement group1 # Execute when the condition is Trueelse: Statement group2 # Execute when the condition is False
Example
Example 1: Judge odd and even numbers
# Determine whether a number is an odd or even numbernum = 15 if num % 2 == 0: print(f"{num}It's an even number") else: print(f"{num}It's an odd number")
Running results:
15It's an odd number
Example 2: Login Verification
# Simple user login verificationusername = "admin" password = "12345" input_username = "admin" input_password = "12345" if username == input_username and password == input_password: print("Login successfully! Welcome back.") else: print("The username or password is incorrect, please try again.")
Running results:
Login successfully!Welcome back。
if…elif…else structure
The if…elif…else structure is used to check multiple conditions. Once a certain condition is met, the corresponding code block is executed and the entire condition structure is popped up. The syntax is as follows:
if Conditional expression1: Statement group1 # Execute when condition 1 is Trueelif Conditional expression2: Statement group2 # Execute when condition 1 is False and condition 2 is Trueelif Conditional expression3: Statement group3 # Execute when conditions 1 and 2 are False and condition 3 is True... else: Statement groupn # Execute when all conditions are False
Example
Example 1: Rating of grades
# Give ratings based on scoresscore = 85 if score >= 90: grade = "A" elif score >= 80: grade = "B" elif score >= 70: grade = "C" elif score >= 60: grade = "D" else: grade = "F" print(f"The score is{score},Rating as{grade}")
Running results:
The score is85,Rating asB
Example 2: Seasonal judgment
#Judge season based on month (Northern Hemisphere)month = 7 if month in [12, 1, 2]: season = "winter" elif month in [3, 4, 5]: season = "spring" elif month in [6, 7, 8]: season = "summer" elif month in [9, 10, 11]: season = "autumn" else: season = "The month is incorrect" print(f"{month}The month is{season}")
Running results:
7The moon is summer
Nested conditional statements
Conditional statements can be used in nesting, that is, other conditional statements are included inside one conditional statement.
#Nested conditional statement example - Simple calculatornum1 = 10 num2 = 5 operation = "+" if operation == "+": result = num1 + num2 elif operation == "-": result = num1 - num2 elif operation == "*": result = num1 * num2 elif operation == "/": if num2 == 0: # Nested conditional statements print("Error: Divider cannot be zero") result = "Undefined" else: result = num1 / num2 else: print("Unsupported operations") result = "Undefined" print(f"{num1} {operation} {num2} = {result}")
Running results:
10 + 5 = 15
Conditional expression (ternary operator)
Python also provides conditional expressions (also known as ternary operators), which are simplified versions of the if-else statement:
value_if_true if condition else value_if_false
Example
# Use conditional expressions to determine sizea = 10 b = 20 maximum = a if a > b else b print(f"The larger number is: {maximum}")
Running results:
The larger number is: 20
Practical application cases
Case 1: Simple login system
# Simple login systemdef login_system(): # Preset user information users = { "admin": "admin123", "user1": "password1", "user2": "password2" } username = input("Please enter the username: ") password = input("Please enter your password: ") if username in users: if users[username] == password: print(f"Welcome back,{username}!") else: print("Error password!") else: print("The user does not exist!") register = input("Do you want to register a new user?(yes/no): ") if () == "yes": print("The registration function is under development...") else: print("Thank you for using it, goodbye!") # Call function# login_system() # Uncomment to run interactive login system
Case 2: Number guessing game
import random def guess_number_game(): # Generate random numbers between 1-100 target = (1, 100) attempts = 0 max_attempts = 7 print("Welcome to the number guessing game!") print(f"I've already thought of one1-100Numbers between,You have{max_attempts}Guess it once a chance。") while attempts < max_attempts: try: guess = int(input("Please enter your guess: ")) attempts += 1 if guess < 1 or guess > 100: print("Please enter a number between 1-100!") continue if guess < target: print("Too small!") elif guess > target: print("Too big!") else: print(f"congratulations,Guessed correctly!The answer is{target}。") print(f"You used it{attempts}Try this。") break if attempts < max_attempts: print(f"You still have{max_attempts - attempts}Time chance。") except ValueError: print("Please enter a valid number!") if attempts == max_attempts and guess != target: print(f"game over!The correct answer is{target}。") # Call function# guess_number_game() # Uncomment to run the guessing game
Summarize
This is the article about the introduction of Python conditional statements and detailed explanations. For more related Python conditional statements, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!