P

Control Flow

Python syntax guide

Conditional statements and loops in Python

Control Flow

Conditional statements and loops in Python

Python control flow (python)
        
          # Conditional statements
age = 25

if age < 18:
    print("Minor")
elif age < 65:
    print("Adult")
else:
    print("Senior")

# Ternary operator
status = "Adult" if age >= 18 else "Minor"

# For loops
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
    print(fruit)

# Range-based loop
for i in range(5):
    print(i)  # 0, 1, 2, 3, 4

# Enumerate for index and value
for index, fruit in enumerate(fruits):
    print(f"{index}: {fruit}")

# While loop
count = 0
while count < 5:
    print(count)
    count += 1

# List comprehensions
squares = [x**2 for x in range(10)]
even_squares = [x**2 for x in range(10) if x % 2 == 0]

# Dictionary comprehension
squares_dict = {x: x**2 for x in range(5)}
print(squares_dict)  # {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}
        
      

Explanation

Python provides clean syntax for control flow. List comprehensions offer concise way to create lists, while enumerate() provides both index and value in loops.

Common Use Cases

  • Conditional logic
  • Iterating over collections
  • Data transformation
  • Filtering data

Related Python Syntax

Master Control Flow in Python

Understanding control flow is fundamental to writing clean and efficient Python code. This comprehensive guide provides you with practical examples and detailed explanations to help you master this important concept.

Whether you're a beginner learning the basics or an experienced developer looking to refresh your knowledge, our examples cover real-world scenarios and best practices for using control flow effectively in your Python projects.

Key Takeaways

  • Conditional logic
  • Iterating over collections
  • Data transformation