Python Control Statements

Python Control Statements

Navigating Python's Flow: Control Statements Demystified

Python Control Statements: Control statements are crucial in Python programming for managing code flow and behavior.

They come in conditional, loop, and control flow statements, and understanding their functions helps in writing well-structured, functional code that requires a comprehension of control statements, regardless of your level of programming proficiency in Python.

  • Conditional Statements

  • Loop Statements

  • Control Flow Statements

Conditional Statements

  1. IF Statement

  2. IF … Else Statement

  3. IF … Else IF … Else Statement

  4. Nested IF

`IF` Statement

" if statement to execute a block of code if a condition is True."

  • Python's decision-making construct is the if statement, enabling programmers to evaluate conditions and execute code blocks based on them.

  • Indentation is used to define the scope of the code block.

  • Curly braces are not required.

💡
Unlike some other languages like C, Python does not require curly braces for code blocks; instead, it relies on indentation to define the scope of code within an if statement

Syntax

if condition:
    # Code to execute if the condition is true

Example 1: Checking User Authentication

In this example, the if statement checks if the entered username and password match the expected values, allowing or denying access accordingly.

# User authentication example
username = input("Enter your username: ")
password = input("Enter your password: ")

if username == "admin" and password == "password123":
    print("Authentication successful. Welcome, admin!")
else:
    print("Authentication failed. Please check your credentials.")

IF … Else Statement

"if-else statement is used when you want to execute one block of code if a condition is True and another block if the condition is False"

Syntax

if condition:
    # Code to execute if the condition is true
else:
    # Code to execute if the condition is false

Example 2: Checking if a year is a leap year

The if statement checks if a year is a leap year using Gregorian calendar rules, enabling Python to make decisions and control program flow, enabling dynamic and responsive programs.

# Checking if a year is a leap year
year = int(input("Enter a year: "))

if (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0):
    print(f"{year} is a leap year.")
else:
    print(f"{year} is not a leap year.")

IF … Else IF … Else Statement

"The if-elif-else statement enables you to assess several conditions sequentially and execute various code blocks depending on the first true condition detected."

Example 3: Grading students based on their score

#Grading Students based on their 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}.")

The 'if-elif-else' statement evaluates a student's score and assigns a corresponding letter grade.

Nested IF

"Nested-if statements in Python create complex decision-making structures by evaluating conditions within conditions."

Syntax

if condition1:
    # Outer if block
    if condition2:
        # Code to execute if condition1 and condition2 are true
    else:
        # Code to execute if condition1 is true, but condition2 is false
else:
    # Code to execute if condition1 is false

Example 4: Checking eligibility for a loan with nested if statements

credit_score = int(input("Enter your credit score:"))
income = float(input("Enter your annual income:"))

if credit_score >= 700:
    if income >= 50000:
       loan_amount = 100000
    else: 
       loan_amount = 50000
else: 
    loan_amount = 0
if loan_amount >0:
     print(f"Congratulations! You are eligible for a ${loan_amount} loan.")
else: 
     print("Sorry, you are not eligiable for a loan at this time.")

The example uses nested if statements to evaluate income conditions, determine loan amounts if credit_score is above or equal to 700 and if not, set loan_amount to 0.

💡
Nested-if statements can be used to create more intricate decision-making logic when multiple conditions need to be checked hierarchically.

Loop Statements

"Loop statements in Python are used to execute a block of code repeatedly, allowing you to automate tasks and process data efficiently."

For loops

When you have a known or iterable sequence (such as lists, tuples, or strings) or when you wish to iterate a certain number of times, you use loops.

They are frequently employed for iterating through elements in a collection or sequence.

Syntax

for element in iterable:
    # Code to execute in each iteration

Example 5

# Iterating through a list of student names and printing a greeting for each
Employee = ["Sanjay", "Amit", "Shashank", "David"]
for employee in employee:
    print(f"Hello, {employee}!")
# Counting the number of vowels in a given string
text = "Hello, World!"
vowel_count = 0

for char in text:
    if char.lower() in "aeiou":
        vowel_count += 1

print(f"There are {vowel_count} vowels in the text.")

# Printing numbers from 1 to 10 using a for loop with 'range'
for number in range(1, 11):
    print(number)
# Iterating through a dictionary of student grades and displaying results
grades = {"Alice": 95, "Bob": 88, "Charlie": 78, "David": 92}

for student, score in grades.items():
    if score >= 90:
        result = "Excellent"
    elif score >= 80:
        result = "Good"
    elif score >= 70:
        result = "Average"
    else:
        result = "Needs Improvement"

    print(f"{student}: {score} ({result})")

While loops

"while loops are particularly useful when you want to repeat a block of code an unknown number of times, such as when waiting for user input or processing data until a specific condition is met."

while condition:
    # Code to execute as long as the condition is true

Example 6: Simulating a password-guessing game using a while loop

# Simulating a password guessing game using a while loop
correct_password = "secret"
attempts = 3

while attempts > 0:
    guess = input("Enter the password: ")

    if guess == correct_password:
        print("Congratulations! You've guessed the correct password.")
        break  # Exit the loop when the password is correct
    else:
        attempts -= 1
        print(f"Incorrect password. You have {attempts} attempts left.")

    if attempts == 0:
        print("Out of attempts. Access denied.")

A while loop simulates a password guessing game, running until the attempts variable is greater than 0. If the user enters the correct password, the loop breaks and the number of attempts decreases until the user guesses the correct password or runs out.

Control Flow Statements

  • Break

  • Continue

  • Return

Break

"Using the break statement, you can end a loop before the condition of the loop is met"

for variable in iterable:
    if condition:
        break

Example 7: Searching for a specific item in a list and using 'break' to exit the loop when found

# List of programming languages
programming_languages = ["Python", "Java", "JavaScript", "C++", "Ruby"]

language_to_find = "JavaScript"
found = False

for language in programming_languages:
    if language == language_to_find:
        found = True
        break  # Exit the loop when the language is found

if found:
    print(f"{language_to_find} is in the list of programming languages.")
else:
    print(f"{language_to_find} is not in the list of programming languages.")

Continue

"The continue statement is useful when you want to selectively process elements in a loop and skip certain iterations based on specific conditions."

for variable in iterable:
    if condition:
        continue
    # Code here will be skipped for the current iteration if the condition is met

Example 8: Skipping even numbers and displaying only odd numbers using 'continue'

# Skipping even numbers and displaying only odd numbers using 'continue'
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

print("Odd numbers:")
for number in numbers:
    if number % 2 == 0:
        continue  # Skip even numbers
    print(number)

For loop iterates through 1-10 numbers, skips even numbers using the continue statement, and prints only odd numbers to the console.

Return

"The return statement allows functions to provide values as output, making it a fundamental part of building reusable and modular code in Python."

def my_function():
    return value

Example 9: Calculates the factorial of a number

# A function that calculates the factorial of a number
def factorial(n):
    if n == 0:
        return 1  # Return 1 for the base case
    else:
        result = n * factorial(n - 1)  # Recursive calculation
        return result  # Return the calculated result

# Calculate the factorial of a number
number = 5
result = factorial(number)

# Display the result
print(f"The factorial of {number} is {result}")

Pass Statement

"Use the pass statement to indicate that we intend to implement this logic later."

The pass statement is a no-op placeholder in Python, used as a temporary placeholder for a statement without specific action, and often used in code for future implementation.

Syntax

def my_function():
    # TODO: Implement this function later
    pass

Example 10: Salary calculation

#When the pass statement is encountered, Python does nothing and continues with the next statement.
class Employee:
    def __init__(self, name, employee_id):
        self.name = name
        self.employee_id = employee_id
        self.salary = 0  # Placeholder for salary calculation

    def calculate_salary(self):
        # TODO: Implement salary calculation logic
        pass

# Let's create some employee instances:
employee1 = Employee("John Doe", 101)
employee2 = Employee("Jane Smith", 102)

#  calculate the salaries for these employees.
employee1.calculate_salary()  # implement this method later
employee2.calculate_salary() # No action is taken, but the code runs without errors

The example uses a pass statement to indicate future implementation of the calculate_salary method for each employee, allowing for code development without syntax errors.

Assertion Statement

"The assert statement is a debugging and testing tool that evaluates expressions and raises an AssertionError exception if they're False. It checks if conditions are true or false, indicating unexpected behavior."

Syntax

assert <condition>
assert <condition>,<error message>

Example 11: Calculating the discounted price

def calculate_discount(price, discount_percentage):
    assert 0 <= discount_percentage <= 100, "Invalid discount percentage"
    discounted_price = price - (price * (discount_percentage / 100))
    return discounted_price
#calculate_discount function
try:
    discounted_price1 = calculate_discount(100, 20)  # Valid discount percentage
    print("Discounted Price 1:", discounted_price1)
except AssertionError as e:
    print("Error:", e)

try:
    discounted_price2 = calculate_discount(100, 150)  # Invalid discount percentage
    print("Discounted Price 2:", discounted_price2)
except AssertionError as e:
    print("Error:", e)

The assert statement checks if the discount percentage is within the valid range (0-100) before calculating the discounted price. If true, the function proceeds, but if false, it raises an AssertionError, indicating the discount percentage is invalid.

Summary
To write attractive and effective code, developers must master Python control statements. These assertions make it possible to make decisions, repeat operations, and deftly navigate complicated algorithms. While loop statements provide for effective data processing, conditional statements enable dynamic programming. Code execution is made more elegant by control flow statements like "break," "continue," and "return." Being able to comprehend these lines improves Python programming abilities and enables smooth code execution.

Did you find this article valuable?

Support ByteScrum Technologies by becoming a sponsor. Any amount is appreciated!