DEV Community

Rain Leander
Rain Leander

Posted on

Control Structures

In Python, control structures are essential constructs that allow programmers to control the flow of execution of a program. Control structures include if-else statements, loops, and functions. In this blog post, we will explore each of these control structures in detail, including their syntax, properties, and usage.

If-Else Statements

If-else statements are used to make decisions in a program. They evaluate a condition and execute a block of code if the condition is true, or another block of code if the condition is false.

For example, the following code snippet uses an if-else statement to check if a number is even or odd:

num = 5

if num % 2 == 0:
    print(num, "is even")
else:
    print(num, "is odd")
Enter fullscreen mode Exit fullscreen mode

Output:

5 is odd
Enter fullscreen mode Exit fullscreen mode

Loops

Loops are used to execute a block of code repeatedly. Python supports two types of loops: for loops and while loops.

For Loops

For loops are used to iterate over a sequence of elements, such as a list, tuple, or dictionary. The loop variable takes on each element of the sequence in turn, and the block of code inside the loop is executed for each element.

For example, the following code snippet uses a for loop to iterate over a list of numbers and print each number:

numbers = [1, 2, 3, 4, 5]

for num in numbers:
    print(num)
Enter fullscreen mode Exit fullscreen mode

Output:

1
2
3
4
5
Enter fullscreen mode Exit fullscreen mode

While Loops

While loops are used to execute a block of code repeatedly as long as a condition is true. The condition is evaluated at the beginning of each iteration, and the block of code inside the loop is executed only if the condition is true.

For example, the following code snippet uses a while loop to print the first 5 numbers:

num = 1

while num <= 5:
    print(num)
    num += 1
Enter fullscreen mode Exit fullscreen mode

Output:

1
2
3
4
5
Enter fullscreen mode Exit fullscreen mode

Functions

Functions are used to encapsulate a block of code that performs a specific task. Functions can accept input arguments, perform computations, and return output values.

For example, the following code snippet defines a function that takes two arguments and returns their sum:

def add_numbers(x, y):
    return x + y

result = add_numbers(2, 3)
print(result)
Enter fullscreen mode Exit fullscreen mode

Output:

5
Enter fullscreen mode Exit fullscreen mode

Control structures are fundamental constructs that every Python programmer needs to be familiar with. If-else statements are used to make decisions, while loops and for loops are used to execute code repeatedly, and functions are used to encapsulate and reuse code. By mastering these control structures, you can control the flow of execution of your program and write efficient and effective code.

Top comments (0)