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
IF Statement
IF … Else Statement
IF … Else IF … Else Statement
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:
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.
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:
else:
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.
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
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:
if condition2:
else:
else:
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:
Example 5
Employee = ["Sanjay", "Amit", "Shashank", "David"]
for employee in employee:
print(f"Hello, {employee}!")
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.")
for number in range(1, 11):
print(number)
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 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:
Example 6: 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
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
"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
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
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
Example 8: 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
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
def factorial(n):
if n == 0:
return 1
else:
result = n * factorial(n - 1)
return result
number = 5
result = factorial(number)
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():
pass
Example 10: Salary calculation
class Employee:
def __init__(self, name, employee_id):
self.name = name
self.employee_id = employee_id
self.salary = 0
def calculate_salary(self):
pass
employee1 = Employee("John Doe", 101)
employee2 = Employee("Jane Smith", 102)
employee1.calculate_salary()
employee2.calculate_salary()
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
try:
discounted_price1 = calculate_discount(100, 20)
print("Discounted Price 1:", discounted_price1)
except AssertionError as e:
print("Error:", e)
try:
discounted_price2 = calculate_discount(100, 150)
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.