Master Python if/else Statements with Practical Examples
This tutorial explains Python's selection structure by walking through three hands‑on exercises—checking if a number exceeds 16, determining odd or even, and calculating the day of the year (including leap‑year logic)—complete with code snippets and sample output.
Python programs are organized into three basic structures: sequential, selection (branch), and loop. The article focuses on the selection structure, demonstrating how if and if‑else statements control program flow.
Example 1 : Prompt the user for a number, test whether it is greater than 16, and print a message only when the condition holds.
num = int(input("请输入一个数字:"))
if num > 16:
print(num, "大于16")Example 2 : Prompt for a number, use the modulo operator to decide if it is even or odd, and print the corresponding label.
num1 = int(input("请输入任意一个数字:"))
if num1 % 2 == 0:
print(num1, "是偶数")
else:
print(num1, "是奇数")Example 3 : Read a year, month, and day, then compute which day of the year the date represents. The algorithm adds the days of preceding months, handling February differently for leap years, and finally prints the result.
year = int(input("年:"))
month = int(input("月:"))
day = int(input("日:"))
# Initialize with the current day
days = day
if month > 1:
days += 31
if month > 2:
if (year % 4 == 0 and year % 100 != 0) or year % 400 == 0:
days += 29
else:
days += 28
if month > 3:
days += 31
if month > 4:
days += 30
if month > 5:
days += 31
if month > 6:
days += 30
if month > 7:
days += 31
if month > 8:
days += 31
if month > 9:
days += 30
if month > 10:
days += 31
if month > 11:
days += 30
if month > 12:
days += 31
print("在", year, "年的第", days, "天")The article then shows a sample interaction:
请输入一个数字:20
20大于16
请输入任意一个数字:26
26 是偶数
年:2021
月:2
日:10
在2021年的第41天Through these concrete examples, readers see how if and if‑else statements are written, how conditions are evaluated, and how branching logic can be combined to solve everyday programming tasks.
Lisa Notes
Lisa's notes: musings on daily life, work, study, personal growth, and casual reflections.
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.
