10 Essential Python Flow‑Control Examples
This article presents ten practical Python code examples that illustrate conditional statements, loops, list comprehensions, and exception handling, helping readers master the core flow‑control constructs essential for writing clear and efficient programs.
🚀 Introduction: Flow control is a core concept in programming that determines how code blocks are executed; the following ten Python examples cover conditional branching, looping, and error handling.
1️⃣ Conditional statement (if…elif…else)
score = 85
if score >= 90:
print("优秀")
elif score >= 80:
print("良好")
elif score >= 60:
print("及格")
else:
print("不及格")2️⃣ Nested conditionals
age = 22
is_student = True
if age < 18:
status = "未成年人"
elif age < 60 and is_student:
status = "在校学生"
else:
status = "社会人士"
print(status)3️⃣ Ternary operator
grade = 78
result = "合格" if grade >= 60 else "不合格"
print(result)4️⃣ For‑loop over a sequence
fruits = ['apple', 'banana', 'cherry']
for fruit in fruits:
print(fruit)
# Output:
# apple
# banana
# cherry5️⃣ Counting loop with range()
for i in range(1, 6):
print(i)
# Output:
# 1
# 2
# 3
# 4
# 56️⃣ While‑loop as a conditional loop
count = 0
while count < 5:
print(count)
count += 1
# Output:
# 0
# 1
# 2
# 3
# 47️⃣ Controlling loops with break and continue
for number in range(1, 11):
if number % 2 == 0:
continue # skip even numbers
if number == 5:
break # stop when number reaches 5
print(number)
# Output:
# 1
# 38️⃣ List comprehension with a condition
numbers = [1, 2, 3, 4, 5, 6]
even_numbers = [num for num in numbers if num % 2 == 0]
print(even_numbers) # Output: [2, 4, 6]9️⃣ Exception handling (try…except…finally)
try:
open('non_existent_file.txt', 'r')
except FileNotFoundError:
print("文件未找到!")
finally:
print("无论是否发生异常,这段代码都会被执行。")10️⃣ pass as a placeholder
for _ in range(5):
if _.is_prime: # hypothetical attribute
pass # no operation, placeholder for future code
else:
print(_.value) # print non‑prime values🎯 Conclusion: By studying and practicing these ten examples, readers should gain a deeper understanding of Python's conditional branches, loop controls, and exception handling, which are essential for writing high‑quality, efficient code. Stay tuned to the public account for more Python tutorials.
Test Development Learning Exchange
Test Development Learning Exchange
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.