Table of contents

Control Structures: Loops and Conditional

Control structures are essential for managing the flow of a program. In Python, the primary control structures are conditional statements and loops. This guide will cover these concepts in detail, with examples to help you understand and implement them effectively.

Conditional statements allow you to execute different code blocks based on certain conditions. Python provides if, elif, and else statements for this purpose.

The if statement evaluates a condition and executes the code block if the condition is True.

age = 18 if age >= 18: print("You are an adult.")

The else statement follows an if statement and executes if the if condition is False.

age = 16 if age >= 18: print("You are an adult.") else: print("You are a minor.")

The elif (short for “else if”) statement allows you to check multiple conditions.

age = 16 if age >= 18: print("You are an adult.") elif age >= 13: print("You are a teenager.") else: print("You are a child.")

A program that assigns grades based on a score.

score = int(input("Enter your score: ")) if score >= 90: grade = 'A' elif score >= 80: grade = 'B' elif score >= 70: grade = 'C' elif score >= 60: grade = 'D' else: grade = 'F' print(f"Your grade is: {grade}")

Loops are used to execute a block of code multiple times. Python provides for and while loops for this purpose.

The for loop iterates over a sequence (e.g., list, tuple, string) and executes the code block for each item in the sequence.

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

The range() function generates a sequence of numbers, which is commonly used with for loops.

for i in range(5): print(i)

The while loop executes the code block as long as the condition is True.

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

The break statement is used to exit a loop prematurely.

for i in range(10): if i == 5: break print(i)

The continue statement skips the rest of the code inside the loop for the current iteration and moves to the next iteration.

for i in range(10): if i % 2 == 0: continue print(i)

A program to find prime numbers within a given range.

start = int(input("Enter the start of the range: ")) end = int(input("Enter the end of the range: ")) for num in range(start, end + 1): if num > 1: for i in range(2, num): if (num % i) == 0: break else: print(num)

A program to generate the Fibonacci sequence up to n terms.

n = int(input("How many terms? ")) a, b = 0, 1 count = 0 if n <= 0: print("Please enter a positive integer") elif n == 1: print("Fibonacci sequence up to", n, ":") print(a) else: print("Fibonacci sequence:") while count < n: print(a) nth = a + b a = b b = nth count += 1

Write a program to calculate the factorial of a number using a for loop.

num = int(input("Enter a number: ")) factorial = 1 if num < 0: print("Factorial does not exist for negative numbers") elif num == 0: print("The factorial of 0 is 1") else: for i in range(1, num + 1): factorial *= i print(f"The factorial of {num} is {factorial}")

Write a program where the user has to guess a secret number between 1 and 100. The program should provide feedback if the guess is too high, too low, or correct.

import random secret_number = random.randint(1, 100) guess = None while guess != secret_number: guess = int(input("Guess the number (between 1 and 100): ")) if guess < secret_number: print("Too low!") elif guess > secret_number: print("Too high!") else: print("Congratulations! You guessed the number.")

In this section, we’ve explored Python’s control structures, including conditional statements (if, elif, else) and loops (for, while). These structures are crucial for controlling the flow of your programs and implementing complex logic. Make sure to practice these concepts with the provided examples and exercises to strengthen your understanding and improve your programming skills. In the next section, we will delve into functions and how they can help you write modular and reusable code. Happy coding!