Understanding Python if...else Statements with Practical Examples
This article explains Python's if...elif...else conditional control structure, presents its basic syntax, and provides a series of clear examples ranging from simple number checks to more complex tasks like recursive Fibonacci, bubble sort, a guessing game, age classification, and bank account balance validation.
Python's if...else statement is a fundamental control flow construct that executes different code blocks based on boolean conditions. The basic syntax is:
if condition:
# code when condition is True
pass
else:
# code when condition is False
passBelow are several illustrative examples.
Example 1: Simple if‑else to check sign of a number
number = int(input("请输入一个整数:"))
if number > 0:
print("这是一个正数。")
elif number < 0:
print("这是一个负数。")
else:
print("这是零。")Example 2: Grade classification
score = 75
if score >= 90:
grade = "A"
elif score >= 80:
grade = "B"
elif score >= 70:
grade = "C"
else:
grade = "D"
print(f"成绩等级为: {grade}")Example 3: Leap year determination
year = 2024
if (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0):
print(f"{year} 是闰年")
else:
print(f"{year} 不是闰年")Example 4: Weather‑based output
weather = "sunny"
if weather == "rainy":
print("带伞出门")
elif weather == "cloudy":
print("可能需要外套")
else:
print("享受好天气")Example 5: Simple login verification
username = input("请输入用户名:")
password = input("请输入密码:")
if username == "admin" and password == "123456":
print("登录成功")
else:
print("登录失败")More advanced conditional examples include:
Recursive Fibonacci
def fibonacci(n):
if n <= 0:
print("输入应为正整数")
elif n == 1:
return 0
elif n == 2:
return 1
else:
return fibonacci(n-1) + fibonacci(n-2)
print(fibonacci(10))Bubble sort implementation
def bubble_sort(arr):
n = len(arr)
for i in range(n):
for j in range(0, n-i-1):
if arr[j] > arr[j+1]:
arr[j], arr[j+1] = arr[j+1], arr[j]
return arr
numbers = [64, 34, 25, 12, 22, 11, 90]
sorted_numbers = bubble_sort(numbers)
print("排序后的数组:", sorted_numbers)Number guessing game with limited attempts
import random
secret_number = random.randint(1, 20)
guesses_taken = 0
print('我想了一个1到20之间的数字')
while guesses_taken < 6:
guess = int(input('请猜这个数字: '))
guesses_taken += 1
if guess < secret_number:
print('太小了')
elif guess > secret_number:
print('太大了')
else:
break
if guess == secret_number:
print(f'干得漂亮,你在第{guesses_taken}次尝试中猜到了数字!')
else:
print(f'很遗憾,你没有在6次机会内猜到。我想的数字是{secret_number}')Age‑based population categorization
ages = [24, 55, 18, 30, 68, 15, 75]
categories = []
for age in ages:
if age < 18:
categories.append("未成年人")
elif 18 <= age < 60:
categories.append("成年人")
else:
categories.append("老年人")
print(categories)Bank account balance check with multiple conditions
class BankAccount:
def __init__(self, balance):
self.balance = balance
def withdraw(self, amount):
if amount > self.balance:
print("余额不足")
elif amount < 0:
print("取款金额不能为负")
else:
self.balance -= amount
print(f"成功取出{amount}元,剩余{self.balance}元")
account = BankAccount(1000)
account.withdraw(500) # 成功
account.withdraw(-100) # 错误:取款金额不能为负
account.withdraw(1500) # 错误:余额不足These examples demonstrate how conditional statements can be combined with other Python constructs to solve a wide range of practical programming problems.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
