Skip to main content

Control Structures

Control Structures in Python

Control structures determine the flow of execution in a Python program. They allow you to make decisions, repeat actions, and control how your code behaves. In this section, we'll cover conditional statements and various types of loops.

4.1 Conditional Statements (if-else)

Conditional statements in Python allow you to execute certain blocks of code based on specific conditions.

4.1.1 if Statement

The if statement evaluates a condition. If the condition is True, the block of code inside the if is executed.

# Example of if statement
x = 10
if x > 5:
    print("x is greater than 5")

4.1.2 if-else Statement

If the condition is False, the code inside the else block will be executed.

# Example of if-else statement
x = 3
if x > 5:
    print("x is greater than 5")
else:
    print("x is less than or equal to 5")

4.1.3 if-elif-else Statement

The elif (else if) keyword allows you to check multiple conditions. The code inside the first condition that evaluates to True will be executed.

# Example of if-elif-else statement
x = 5
if x > 5:
    print("x is greater than 5")
elif x == 5:
    print("x is equal to 5")
else:
    print("x is less than 5")

4.2 Loops

Loops allow you to repeatedly execute a block of code as long as a condition is met. Python provides two types of loops: for loops and while loops.

4.2.1 for Loop

The for loop is used for iterating over a sequence (such as a list, tuple, or string).

# Example of a for loop
numbers = [1, 2, 3, 4]
for num in numbers:
    print(num)

4.2.2 while Loop

The while loop continues to execute as long as the condition is True. You should be cautious with while loops to avoid infinite loops.

# Example of a while loop
count = 0
while count < 3:
    print("Counting:", count)
    count += 1

4.3 Loop Control Statements

Python provides loop control statements to alter the flow of a loop.

4.3.1 break Statement

The break statement terminates the loop prematurely, even if the loop condition is still true.

# Example of break statement
for num in range(10):
    if num == 5:
        break  # Exit the loop
    print(num)

4.3.2 continue Statement

The continue statement skips the current iteration and moves to the next one.

# Example of continue statement
for num in range(5):
    if num == 2:
        continue  # Skip iteration when num is 2
    print(num)

4.3.3 pass Statement

The pass statement is used as a placeholder. It does nothing and is used in cases where syntactically some code is required, but you want to do nothing.

# Example of pass statement
for num in range(5):
    if num == 3:
        pass  # Do nothing for num == 3
    print(num)

4.4 Nested Loops

Python allows you to use loops inside loops. This is useful when you want to iterate over a sequence within another sequence.

# Example of nested loops
for i in range(1, 4):
    for j in range(1, 3):
        print(f"i={i}, j={j}")

4.5 else with Loops

In Python, you can use an else block with both for and while loops. The else block is executed when the loop finishes its normal iteration (i.e., not interrupted by a break).

# Example of else with for loop
for num in range(3):
    print(num)
else:
    print("Loop finished successfully")
# Example of else with while loop
count = 0
while count < 3:
    print(count)
    count += 1
else:
    print("Loop finished successfully")

4.6 Conclusion

In this section, we explored control structures in Python, including conditional statements, loops, and advanced control flow techniques like break, continue, and pass. Understanding these concepts is crucial for controlling how your programs behave and making decisions based on different conditions.

Comments

Popular posts from this blog

Arrays, Lists, and LinkedLists in Java

Arrays, Lists, and LinkedLists in Java Understanding the differences between arrays, lists, and linked lists is fundamental in Java programming. Each data structure has its unique characteristics and use cases. This guide will delve into how these structures work, their advantages and disadvantages, and provide examples of how to use them in Java. 1. Arrays in Java An array is a fixed-size data structure that stores elements of the same type in contiguous memory locations. Arrays are one of the simplest and most commonly used data structures in Java. 1.1 Declaring and Initializing Arrays You can declare and initialize an array as follows: public class ArrayExample { public static void main(String[] args) { // Declaration and initialization int[] numbers = new int[5]; // Array of integers with size 5 numbers[0] = 10; numbers[1] = 20...

Guide to Creating and Executing C Executables with Shared Libraries and Java Integration

Guide to Creating and Executing C Executables with Shared Libraries and Java Integration 1. Compiling a C Program to an Executable Step 1: Write a C Program #include <stdio.h> int main() { printf("Hello, World!\\n"); return 0; } Step 2: Compile the C Program gcc -o example example.c 2. Executing the C Program in the Console Step 3: Run the Executable ./example 3. Including Shared .so Libraries Step 4: Create a Shared Library #include <stdio.h> void my_function() { printf("Shared Library Function Called!\\n"); } gcc -shared -o libmylib.so -fPIC mylib.c Step 5: Update the C Program to Use the Shared Library #include <stdio.h> void my_function(); int main() { my_function(); printf("Hello, World!\\n...

Mastering Java Maps

In Java, maps are a versatile and powerful data structure that allow for the efficient storage and retrieval of key-value pairs. This document will cover various aspects of using maps in Java, from basic operations to advanced use cases. Overview of Maps Maps are part of the Java Collections Framework and provide a way to store data in key-value pairs. The keys are unique, and each key maps to exactly one value. Maps are crucial for tasks where quick lookups, insertions, and deletions are needed. Types of Maps Java provides several implementations of the Map interface, each with different characteristics: HashMap: Stores key-value pairs in a hash table. It does not guarantee any order of its elements. It allows one null key and multiple null values. LinkedHashMap: Extends HashMap and maintains a doubly-linked...