Control structures in Python are essential tools for building complex systems. They allow developers to control the flow of code execution, making programming more flexible and powerful. In this chapter, we'll explore four fundamental control structures in Python: if-else, for loops, while loops, and try-except.
1. If-Else
The if-else control structure is one of the most basic in Python. It allows code to make decisions based on conditions. See an example:
x = 10 if x > 0: print("x is positive") else: print("x is negative or zero")
In this example, if x is greater than zero, the program will print "x is positive". Otherwise it will print "x is negative or zero". You can add more conditions using elif, which is short for "else if".
2. For Loops
For loops in Python are used to iterate over a sequence (such as a list, tuple, dictionary, set, or string) or an iterable object. See an example:
fruits = ["apple", "banana", "mango"] for fruit in fruit: print(fruit)
In this example, the program will print each fruit in the fruit list. The variable fruit is a loop variable, which takes on the value of each element in the sequence during each iteration of the loop.
3. While Loops
The while loops in Python are used to repeat a block of code while a condition is true. See an example:
x = 5 while x > 0: print(x) x -= 1
In this example, the program will print the value of x and then decrement x by 1. The loop will continue as long as x is greater than zero.
4. Try-Except
The try-except control structure in Python is used to handle exceptions. An exception is an event that occurs during program execution that interrupts the normal flow of instructions. See an example:
try: x = 1 / 0 except ZeroDivisionError: print("You tried to divide by zero!")
In this example, the program will try to execute the code inside the try block. If a ZeroDivisionError exception occurs, the program will execute the code inside the except block, printing "You tried to divide by zero!".
These four control structures are fundamental to programming in Python. With them, you can control the flow of code execution, make decisions, repeat blocks of code, and handle exceptions. In the next chapter, we'll explore functions in Python, which are reusable blocks of code that perform a specific task.