Python
  • Intro.
  • Catalogue
  • Chapter 1: Introduction to Python
  • Chapter 2: Python Syntax and Fundamentals
    • Chapter: Variables and Data Types in Python
  • Chapter 3: Control Flow
  • Chapter 4: Functions
  • Chapter 5: Data Structures
  • Chapter 6: Object-Oriented Programming (OOP)
  • Chapter 7: Modules and Packages
  • Chapter 8: File Handling
  • Chapter 9: Error and Exception Handling
  • Chapter 10: Working with Databases
  • Chapter 11: Iterators and Generators
  • Chapter 12: Decorators and Context Managers
  • Chapter 13: Concurrency and Parallelism
  • Chapter 14: Testing and Debugging
  • Chapter 15: Web Development with Python
  • Chapter 16: Data Science and Machine Learning with Python
  • Chapter 17: Working with APIs
  • Chapter 18: Automation with Python
  • Chapter 19: Python and Cloud/DevOps
  • Chapter 20: Python and IoT
  • Appendices
Powered by GitBook
On this page
  • 1. Conditional Statements
  • 2. Loops
  • 3. Control Flow Tools
  • 4. Comprehensions
  • 5. Precautions and Tricks
  • Summary Table: Control Flow Tools

Chapter 3: Control Flow


1. Conditional Statements

Conditional statements execute different code blocks based on conditions.

1.1 if Statement

The simplest form of control flow. If a condition is True, the code inside the if block is executed.

Syntax:

if condition:
    # Code to execute if the condition is True

Example:

age = 18
if age >= 18:
    print("You are an adult.")

1.2 if-else Statement

Provides an alternative code block if the condition is False.

Syntax:

if condition:
    # Code to execute if the condition is True
else:
    # Code to execute if the condition is False

Example:

num = 10
if num % 2 == 0:
    print("Even number.")
else:
    print("Odd number.")

1.3 if-elif-else Statement

Tests multiple conditions in sequence.

Syntax:

if condition1:
    # Code if condition1 is True
elif condition2:
    # Code if condition2 is True
else:
    # Code if none of the above conditions are True

Example:

score = 85
if score >= 90:
    print("Grade: A")
elif score >= 80:
    print("Grade: B")
else:
    print("Grade: C")

1.4 Nested if Statements

if statements can be nested for more complex conditions.

Example:

age = 20
has_id = True

if age >= 18:
    if has_id:
        print("Access granted.")
    else:
        print("ID required.")
else:
    print("Access denied.")

1.5 Ternary Conditional Expression

A one-liner for if-else statements.

Syntax:

value = true_value if condition else false_value

Example:

age = 20
status = "Adult" if age >= 18 else "Minor"
print(status)

1.6 Precautions with Conditionals

  1. Proper Indentation: Python relies on indentation to define blocks. A mismatch will cause errors.

  2. Avoid Overcomplicating: Use elif instead of nesting multiple if statements.

  3. Boolean Values: Avoid redundancy. For example, instead of:

    if x == True:

    Simply use:

    if x:

2. Loops

Loops allow you to execute code repeatedly.

2.1 while Loop

Repeats as long as a condition is True.

Syntax:

while condition:
    # Code to execute repeatedly

Example:

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

Precautions:

  • Infinite Loops: Ensure the condition eventually becomes False.

  • Use a break statement to exit loops if necessary.


2.2 for Loop

Iterates over a sequence (e.g., list, string, range).

Syntax:

for variable in sequence:
    # Code to execute for each item in the sequence

Example:

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

2.3 range() in for Loops

The range() function generates a sequence of numbers, commonly used in for loops.

Examples:

for i in range(5):  # 0 to 4
    print(i)

for i in range(2, 10, 2):  # Start at 2, end at 9, step by 2
    print(i)

2.4 break and continue

  • break: Exit the loop entirely.

  • continue: Skip to the next iteration.

Examples:

for i in range(5):
    if i == 3:
        break
    print(i)  # Stops when i == 3

for i in range(5):
    if i == 2:
        continue
    print(i)  # Skips i == 2

2.5 Nested Loops

Loops inside other loops.

Example:

for i in range(3):
    for j in range(2):
        print(f"i={i}, j={j}")

3. Control Flow Tools

3.1 The pass Statement

Does nothing; acts as a placeholder.

Example:

if True:
    pass  # Placeholder for future code

3.2 The else Clause in Loops

A for or while loop can have an else clause. The else block runs if the loop completes normally (i.e., no break).

Example:

for i in range(5):
    if i == 3:
        break
else:
    print("Loop completed.")

4. Comprehensions

4.1 List Comprehensions

A concise way to create lists.

Example:

squares = [x**2 for x in range(5)]
print(squares)  # [0, 1, 4, 9, 16]

4.2 Dictionary Comprehensions

Create dictionaries in one line.

Example:

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

5. Precautions and Tricks

  1. Avoid Infinite Loops:

    • Always ensure the loop condition will eventually be False.

  2. Keep Logic Simple:

    • Use comprehensions where possible for clarity and efficiency.

  3. Don’t Modify a Collection While Iterating:

    • If you need to modify a list while looping, iterate over a copy:

      for item in list(items):
          items.remove(item)
  4. else in Loops:

    • Remember that the else block executes only if the loop wasn't terminated by break.


Summary Table: Control Flow Tools

Control Flow Tool
Description
Example

if

Executes block if condition is True.

if x > 5: print(x)

if-else

Adds an alternative block.

if x > 5: ... else: ...

if-elif-else

Tests multiple conditions.

if x > 5: ... elif x == 5: ...

while

Repeats as long as condition is True.

while x < 5: ...

for

Iterates over a sequence.

for item in list: ...

break

Exits the loop entirely.

if x == 3: break

continue

Skips to the next iteration.

if x == 3: continue

pass

Does nothing (placeholder).

if x > 5: pass

else in loops

Executes if loop completes normally.

for x in range(5): ... else: ...

Comprehensions

One-line list or dict creation.

[x**2 for x in range(5)]


PreviousChapter: Variables and Data Types in PythonNextChapter 4: Functions

Last updated 4 months ago