Python control flow statements are constructs used to control the flow of execution within a Python program. Python control flow statements are powerful tools that dictate how your program executes. They allow your code to make decisions, repeat tasks conditionally, and organize instructions efficiently.
IF-Elif-Else
Syntax:
if Boolean_condition:
True statement
elif Boolean_condition:
True statement
elif Boolean_condition:
True statement
else:
False statement
Q:- How to get Prime Number greater than 5 and Less than 58?
Answer:-
def is_prime(num):
"""Checks if a number is prime."""
if num <= 1:
return False
for i in range(2, int(num**0.5) + 1):
if num % i == 0:
return False
return True
prime_numbers = []
for num in range(6, 58):
if is_prime(num):
prime_numbers.append(num)
print(f"Prime numbers between 5 and 58 (inclusive): {prime_numbers}")
Iterate through numbers from 6 to 57 and check if they’re prime
prime_numbers = [num for num in range(6, 58) if is_prime(num)]
print("Prime numbers greater than 5 and less than 58:", prime_numbers)
Q:How to generate a Fibonacci series within the range of 5 to 56?
Ternary operator in Python
if-else: True if condition else False
if-elif-else: True_for_if if cond1 else True_for_elif if cond2 else False
# Example: Equilateral triangle
sideA, sideB, sideC = -3,-3,-3
if sideA == sideB == sideC and sideA>0:
print("It is equilateral")
else:
print("Not an equilateral")
# Same code with ternary operatot
print("It is equilateral") if sideA == sideB == sideC and sideA>0 else print("Not an equilateral")
Examples:
1. Grading System
This example assigns grades based on a score using if-elif-else
statements.
def assign_grade(score):
if score >= 90:
return 'A'
elif score >= 80:
return 'B'
elif score >= 70:
return 'C'
elif score >= 60:
return 'D'
else:
return 'F'
scores = [95, 82, 67, 58, 91, 76]
grades = [assign_grade(score) for score in scores]
print(f"Scores: {scores}")
print(f"Grades: {grades}")
2. Complex Decision-Making
This example decides what to wear based on temperature and weather conditions.
def decide_outfit(temp, weather):
if temp > 30:
if weather == 'sunny':
return 'T-shirt and shorts'
elif weather == 'rainy':
return 'Raincoat and shorts'
elif 20 <= temp <= 30:
if weather == 'sunny':
return 'T-shirt and jeans'
elif weather == 'rainy':
return 'Raincoat and jeans'
else:
if weather == 'sunny':
return 'Sweater and jeans'
elif weather == 'rainy':
return 'Raincoat and warm clothes'
return 'Check the weather again!'
print(decide_outfit(32, 'sunny')) # T-shirt and shorts
print(decide_outfit(25, 'rainy')) # Raincoat and jeans
print(decide_outfit(15, 'sunny')) # Sweater and jeans
print(decide_outfit(10, 'rainy')) # Raincoat and warm clothes
3. Complex Ternary Operations
This example shows how to use nested ternary operators to determine ticket prices based on age and membership status.
def ticket_price(age, is_member):
return 5 if age < 18 else 10 if age < 60 else 7 if is_member else 12
ages = [15, 25, 65, 70]
membership_status = [True, False, True, False]
prices = [ticket_price(age, member) for age, member in zip(ages, membership_status)]
print(f"Ticket prices: {prices}")
4. Nested Conditions for Loan Approval
This example evaluates whether a person qualifies for a loan based on several criteria.
def loan_approval(credit_score, income, employment_status):
if credit_score >= 700:
if income > 50000:
return 'Approved'
elif income > 30000:
if employment_status == 'full-time':
return 'Approved with conditions'
else:
return 'Not Approved'
else:
return 'Not Approved'
elif 600 <= credit_score < 700:
if income > 60000 and employment_status == 'full-time':
return 'Approved with high interest rate'
else:
return 'Not Approved'
else:
return 'Not Approved'
applicants = [
(720, 60000, 'full-time'),
(680, 40000, 'part-time'),
(650, 70000, 'full-time'),
(590, 30000, 'unemployed')
]
decisions = [loan_approval(*applicant) for applicant in applicants]
print(f"Loan decisions: {decisions}")
5. Weather Report Using Nested Ternary Operators
This example gives a weather report based on temperature and humidity using nested ternary operators.
def weather_report(temp, humidity):
return (
"Hot and Humid" if temp > 30 and humidity > 60 else
"Hot and Dry" if temp > 30 and humidity <= 60 else
"Warm and Humid" if 20 <= temp <= 30 and humidity > 60 else
"Warm and Dry" if 20 <= temp <= 30 and humidity <= 60 else
"Cool and Humid" if temp < 20 and humidity > 60 else
"Cool and Dry"
)
conditions = [
(32, 65),
(28, 55),
(18, 70),
(15, 50)
]
reports = [weather_report(temp, humidity) for temp, humidity in conditions]
print(f"Weather reports: {reports}")
6. Evaluating Expressions Based on User Input
This example evaluates mathematical expressions based on user input and prints the result using if-elif-else
statements.
def evaluate_expression(x, operation):
if operation == 'square':
return x ** 2
elif operation == 'cube':
return x ** 3
elif operation == 'double':
return x * 2
elif operation == 'half':
return x / 2
else:
return 'Invalid operation'
inputs = [
(4, 'square'),
(3, 'cube'),
(5, 'double'),
(10, 'half'),
(7, 'unknown')
]
results = [evaluate_expression(x, operation) for x, operation in inputs]
print(f"Results: {results}")
These examples showcase various scenarios where control structures such as if-elif-else
statements and ternary operators can be used to implement complex logic in Python. They illustrate how you can make decisions, evaluate conditions, and handle multiple cases efficiently.
Can every if else elif can be written in ternary operator format
Yes, most if-else statements can be written using ternary operators. However, there are some limitations and exceptions:
Simple If-Else Statements
These can always be converted to ternary operators.
# If-else statement
if condition:
value = 'true_value'
else:
value = 'false_value'
# Equivalent ternary operator
value = 'true_value' if condition else 'false_value'
If-Elif-Else Statements
These can be converted to nested ternary operators, but it’s often less readable.
# If-elif-else statement
if condition1:
value = 'value1'
elif condition2:
value = 'value2'
else:
value = 'value3'
# Equivalent nested ternary operators
value = 'value1' if condition1 else ('value2' if condition2 else 'value3')
If Statements Without Else Clauses
These cannot be directly converted to ternary operators, as ternary operators must have both a “true” and “false” value.
# If statement without else clause
if condition:
value = 'true_value'
# No direct equivalent ternary operator
Multiple Statements in If Blocks
Ternary operators can only evaluate to a single value. If you need to execute multiple statements based on a condition, you cannot use a ternary operator.
# If statement with multiple statements
if condition:
value1 = 'true_value1'
value2 = 'true_value2'
# No direct equivalent ternary operator
Discover more from HintsToday
Subscribe to get the latest posts sent to your email.