Python Control Flow

if/else Statements

Control flow allows you to execute different blocks of code based on specific conditions. The if/else statements are fundamental for this.

          
            num = 10
            if num > 5:
              print("Number is greater than 5")
            else:
              print("Number is not greater than 5")
          
        

This code checks if the variable num is greater than 5. If it is, it prints the first message; otherwise, it prints the second message.

for Loops

for loops are used to iterate over a sequence of items.

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

This code iterates through the fruits list, printing each item in the list.

while Loops

while loops execute a block of code as long as a condition is true.

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

This code initializes a counter variable count to 0. The loop continues as long as count is less than 5. Inside the loop, the value of count is printed, and then it's incremented by 1.