Table of Contents

Control Flow in Python

Table of Contents

Control flow is the order in which statements are executed in a program. In Python, you can use control flow statements to change the order in which statements are executed, depending on certain conditions.

Here are the main control flow statements in Python:

  1. Conditional statements (if/elif/else): These statements allow you to execute different code blocks depending on whether a certain condition is true or false. For example:
    x = 10
    if x < 0:
        print("x is negative")
    elif x == 0:
        print("x is zero")
    else:
        print("x is positive")

    In this example, the if statement checks if x is negative, the elif statement checks if x is zero, and the else statement is executed if neither condition is true.

  2. Loops (while/for): Loops allow you to execute the same block of code multiple times. The while loop executes the code block as long as a certain condition is true, while the for loop executes the code block for each item in a sequence. For example:
    i = 0
    while i < 10:
        print(i)
        i += 1
    
    for x in [1, 2, 3]:
        print(x)

    In this example, the while loop prints the numbers 0 to 9, and the for loop prints the numbers 1 to 3.

  3. Break and continue statements: These statements allow you to modify the behavior of loops. The break statement terminates the loop immediately, while the continue statement skips the current iteration of the loop and goes to the next one. For example:
    i = 0
    while True:
        i += 1
        if i == 10:
            break
        if i % 2 == 0:
            continue
        print(i)

    In this example, the while loop prints the odd numbers from 1 to 9, and the break and continue statements are used to control the flow of the loop.

  4. Pass statement: In Python, pass is a statement that does nothing. It is used as a placeholder in places where a statement is required syntactically, but no code needs to be executed. The pass statement is often used in functions or classes that are not yet implemented, to provide a valid syntactic structure for the code. For example, consider a function that you want to define later, but you want to write the function signature first:
    def my_function():
        pass

    In this example, the pass statement allows you to define a valid function structure without writing any code. You can come back later and fill in the code for the function.

These are the basic control flow statements in Python, and they can be combined to create more complex programs with different behavior based on certain conditions.

Category
Tags

Copyright 2023-24 © Open Code