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 = [num for num in range(6, 58) if is_prime(num)]
print(f"Prime numbers between 5 and 58 (inclusive): {prime_numbers}")
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.
Looping in Python
Type of loops in Python
In Python, there are primarily two fundamental loop constructs for iterating over sequences of elements:
1. for loop:
- Used to iterate over a sequence of elements (like lists, tuples, strings, dictionaries).
- Executes a block of code for each element in the sequence.
Syntax:
Python
for element in sequence:
# Code to be executed for each element
Example:
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
Output:
apple
banana
cherry
2. while loop:
- Executes a block of code as long as a certain condition is true.
- More flexible than
for
loops, as the condition can be based on any logic and may change within the loop.
Syntax:
while condition:
# Code to be executed while the condition is true
Example:
count = 0
while count < 5:
print(count)
count += 1 # Increment count
Output:
0
1
2
3
4
Additional Considerations:
break
statement: Used to exit a loop prematurely when a specific condition is met within the loop.continue
statement: Used to skip the current iteration of the loop and move on to the next one.- Nested Loops: Loops can be nested within each other to create more complex iterations.
Choosing the Right Loop:
- If you know the exact number of elements in a sequence, a
for
loop is typically more concise and readable. - If you need to iterate until a specific condition is met, a
while
loop is more appropriate.
By effectively using these loop constructs, you can automate repetitive tasks and control the flow of your Python programs.
For Loops
The syntax for a for
loop in Python is concise and easy to understand. Here’s a breakdown of its components:
Basic Structure:
for item in iterable:
# code to be executed for each item
Explanation:
for
: This keyword initiates the loop.item
(Variable): This is a placeholder variable that takes on the value of each item in thesequence
during each iteration of the loop. You can choose any meaningful name for this variable.in
: This keyword specifies that you’re looping through the elements in thesequence
.iterable
: This is the iterable object (like a list, string, tuple, etc.) that the loop will iterate over. Thefor
loop will extract each item from the sequence one by one and assign it to theitem
variable.# code to be executed for each item
: This is the indented code block that will be executed for each item in the sequence. The indentation level is crucial! It defines which lines of code are part of the loop body.
Example 1: Looping through a List
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print("I like", fruit)
In this example, the loop iterates over the fruits
list. In each iteration, the current fruit (e.g., “apple” in the first iteration) is assigned to the fruit
variable, and the indented print statement is executed.
Example 2: Looping through a String
name = "Alice"
for letter in name:
print(letter.upper()) # Print each letter in uppercase
Here, the loop iterates over each letter in the name
string. The current letter is assigned to the letter
variable in each iteration, and the print statement converts it to uppercase before printing.
Key Points:
- The
for
loop automatically handles the iteration and stops when it reaches the end of the sequence. - You can use any iterable object (like a dictionary or a custom class with an iterator) in the
sequence
part. - The loop variable (
item
in our examples) is temporary within the loop and cannot be accessed outside of the loop’s indented block.
By mastering the for
loop in Python, you can efficiently iterate over sequences and perform operations on each item, making your code more concise and readable.
Range Function
The range()
function is versatile and widely used in Python for generating sequences of numbers. It’s helpful for iterating over sequences, generating lists of numbers, and various other tasks where you need a series of numbers.
range(start, stop[, step])
- start: The starting value of the sequence (inclusive). If omitted, it defaults to 0.
- stop: The end value of the sequence (exclusive). This is the number up to which the sequence generates values.
- step: The step or increment between each number in the sequence. If omitted, it defaults to 1.
Syntax 1: range(start=0,end=len(sequence),step=1)
list(range(1,5))
[0,1,2,3,4]
list(range(1,10,2))
[1,3,5,7,9]
range(stop)
range(3)
range(3+1)
range(start, stop)
range(2, 6)
range(5,10+1)
range(start, stop, step)
range(4, 15+1, 2)
range(2*2, 25, 3+2)
range(10, 0, -2)
Nested for loops
Nested for loops are a powerful tool in Python, allowing you to perform iterations over multi-dimensional data structures such as lists of lists, matrices, and more. Let’s explore some complex examples to understand nested for loops better.
1. Matrix Addition
Adding two matrices element-wise using nested for loops.
A = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
B = [
[9, 8, 7],
[6, 5, 4],
[3, 2, 1]
]
# Initialize the result matrix with zeros
result = [[0 for _ in range(len(A[0]))] for _ in range(len(A))]
# Perform element-wise addition
for i in range(len(A)):
for j in range(len(A[0])):
result[i][j] = A[i][j] + B[i][j]
print("Result of matrix addition:")
for row in result:
print(row)
2. Transpose of a Matrix
Finding the transpose of a matrix using nested for loops.
matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
# Initialize the transpose matrix with zeros
transpose = [[0 for _ in range(len(matrix))] for _ in range(len(matrix[0]))]
# Compute the transpose
for i in range(len(matrix)):
for j in range(len(matrix[0])):
transpose[j][i] = matrix[i][j]
print("Transpose of the matrix:")
for row in transpose:
print(row)
3. Multiplication Table
Generating a multiplication table using nested for loops.
# Define the size of the multiplication table
size = 10
# Generate the multiplication table
multiplication_table = [[i * j for j in range(1, size + 1)] for i in range(1, size + 1)]
print("Multiplication table:")
for row in multiplication_table:
print(row)
4. Generating Combinations
Generating all possible combinations of elements from two lists using nested for loops.
list1 = ['a', 'b', 'c']
list2 = [1, 2, 3]
combinations = []
for item1 in list1:
for item2 in list2:
combinations.append((item1, item2))
print("All combinations:")
for combination in combinations:
print(combination)
5. Image Processing (Grayscale to Binary)
Converting a grayscale image to a binary image using nested for loops (assuming the image is represented as a 2D list of pixel values).
# Example grayscale image (2D list of pixel values)
grayscale_image = [
[120, 200, 150],
[30, 255, 75],
[100, 180, 220]
]
# Threshold value for binary conversion
threshold = 128
# Initialize binary image
binary_image = [[0 for _ in range(len(grayscale_image[0]))] for _ in range(len(grayscale_image))]
# Convert grayscale to binary
for i in range(len(grayscale_image)):
for j in range(len(grayscale_image[0])):
binary_image[i][j] = 1 if grayscale_image[i][j] > threshold else 0
print("Binary image:")
for row in binary_image:
print(row)
6. Word Search Puzzle
Searching for a word in a 2D grid of characters using nested for loops.
grid = [
['c', 'a', 't'],
['d', 'o', 'g'],
['r', 'a', 't']
]
word = "cat"
found = False
for i in range(len(grid)):
for j in range(len(grid[0])):
# Check if the first character matches and search horizontally
if grid[i][j] == word[0]:
if j + len(word) <= len(grid[0]) and all(grid[i][j + k] == word[k] for k in range(len(word))):
found = True
break
if found:
break
print(f"Word '{word}' found in grid: {found}")
7. Flattening a Nested List
Flattening a nested list using nested for loops.
nested_list = [[1, 2, [3, 4]], [5, 6], [7, 8, [9, 10]]]
def flatten_list(nested):
flat_list = []
for item in nested:
if isinstance(item, list):
flat_list.extend(flatten_list(item))
else:
flat_list.append(item)
return flat_list
flattened_list = flatten_list(nested_list)
print("Flattened list:", flattened_list)
These examples demonstrate the use of nested for loops in various scenarios, including matrix operations, image processing, and working with nested lists. They show how powerful and versatile nested loops can be when dealing with complex data structures.
While Loop in Python
A while loop is a fundamental control flow construct in Python that allows you to execute a block of code repeatedly as long as a certain condition remains true. It’s particularly useful for situations where you don’t know beforehand how many times you need to iterate.
Syntax:
while condition:
# Code to be executed as long as the condition is true
Explanation:
condition
: This is a Boolean expression that determines whether the loop continues to execute. If the condition evaluates toTrue
, the code block within the loop will run. If it evaluates toFalse
, the loop terminates.- Code block: This is the indented block of code that gets executed repeatedly as long as the
condition
holds true.
Example 1: Guessing Game
Python
import random
secret_number = random.randint(1, 100) # Generate a random number between 1 and 100
guess_count = 0
guess_limit = 7
while guess_count < guess_limit:
try:
guess = int(input("Guess a number between 1 and 100: "))
guess_count += 1
if guess == secret_number:
print("Congratulations, you guessed the number in", guess_count, "tries!")
break # Exit the loop if the guess is correct
elif guess < secret_number:
print("Your guess is too low. Try again.")
else:
print("Your guess is too high. Try again.")
except ValueError:
print("Invalid input. Please enter an integer.")
if guess_count == guess_limit:
print("Sorry, you ran out of guesses. The number was", secret_number)
Explanation:
- The program generates a secret number and allows the user to guess it within a set number of attempts (
guess_limit
). - The
while
loop continues as long asguess_count
is less thanguess_limit
. - Inside the loop, the user enters a guess, which is validated to ensure it’s an integer.
- The program checks if the guess is correct, too low, or too high, providing feedback to the user.
- The
break
statement exits the loop if the guess is correct. - The
try-except
block handles potentialValueError
if the user enters non-numeric input.
Example 2: Menu-Driven Program
def display_menu():
print("1. Add numbers")
print("2. Subtract numbers")
print("3. Exit")
choice = 0
while choice != 3:
display_menu()
choice = int(input("Enter your choice: "))
if choice == 1:
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
result = num1 + num2
print("Sum:", result)
elif choice == 2:
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
result = num1 - num2
print("Difference:", result)
elif choice == 3:
print("Exiting program...")
else:
print("Invalid choice. Please try again.")
# Start the program
display_menu()
Explanation:
- This example demonstrates a menu-driven program using a
while
loop. - The loop continues as long as the user doesn’t choose option 3 (Exit).
- Inside the loop, the menu is displayed, and the user’s choice is taken as input and validated.
- Depending on the choice, different functionalities (addition or subtraction) are performed.
- The user can keep entering choices until they choose to exit.
Use Cases:
- Iterating over sequences of elements (lists, tuples, strings, dictionaries)
- Performing calculations repeatedly until a certain condition is met
- Creating menus or interactive programs where the user can choose different options
- Processing data from files or network connections (reading line by line)
- Implementing algorithms that involve repetition based on conditions
By effectively using while loops, you can automate repetitive tasks and control the flow of your Python programs in complex scenarios.
Break, continue and pass in python with examples
In Python, break
, continue
, and pass
are control flow statements used within loops and conditional statements to alter the program’s execution flow. Here’s a breakdown of each statement with examples:
1. break:
- Terminates the loop prematurely when a specific condition is met.
- Control jumps to the statement after the loop (if any).
fruits = ["apple", "banana", "cherry", "orange"]
for fruit in fruits:
if fruit == "cherry":
print(f"Found {fruit}!")
break # Exit the loop after finding cherry
print(fruit)
# Output:
# apple
# banana
# Found cherry!
2. continue:
- Skips the current iteration of the loop and continues with the next iteration.
- The remaining code within the current iteration is not executed.
numbers = [1, 2, 3, 4, 5]
for num in numbers:
if num % 2 == 0: # Skip even numbers
continue
print(num)
# Output:
# 1
# 3
# 5
3. pass:
- Acts as a placeholder within a code block.
- It does nothing but maintains the structure, allowing for an empty statement where Python expects one syntactically.
# Example 1: Empty loop (does nothing)
for i in range(5):
pass # Placeholder, loop iterates but does nothing
# Example 2: Conditional statement without an action (no indentation needed)
if age < 18:
pass # Placeholder, no action for underage users
else:
print("You are eligible.")
Choosing the Right Statement:
- Use
break
to exit a loop early when you’ve found what you’re looking for or a certain condition is met. - Use
continue
to skip specific iterations within a loop based on a condition. - Use
pass
as a placeholder when you need a syntactically valid statement but don’t want any action to occur at that point in your code.
What is while True
loop
A while True
loop in Python creates an infinite loop that runs until it is explicitly stopped, typically using a break
statement or an external condition. This type of loop is useful when you want the program to continue running until a certain condition is met or an event occurs.
Basic Example
Here is a simple example of a while True
loop that repeatedly asks the user for input until they type ‘exit’:
while True:
user_input = input("Enter something (type 'exit' to quit): ")
if user_input.lower() == 'exit':
print("Goodbye!")
break
else:
print(f"You entered: {user_input}")
Common Use Cases
- Interactive Menus: Continuously display a menu until the user chooses to exit.
- Waiting for Events: Wait for an external event or condition to occur.
- Retry Logic: Retry an operation until it succeeds or until a maximum number of retries is reached.
- Real-time Data Processing: Continuously process data from a stream or a sensor.
Example 1: Interactive Menu
def print_menu():
print("Main Menu")
print("1. Option One")
print("2. Option Two")
print("3. Exit")
while True:
print_menu()
choice = input("Enter your choice: ")
if choice == '1':
print("You selected Option One.")
elif choice == '2':
print("You selected Option Two.")
elif choice == '3':
print("Exiting...")
break
else:
print("Invalid choice. Please select a valid option.")
Example 2: Waiting for an Event
import time
print("Waiting for event...")
while True:
# Simulate checking for an event
event_occurred = False # This would be some condition or external event
time.sleep(1) # Wait for 1 second
if event_occurred:
print("Event occurred!")
break
else:
print("No event yet...")
print("Exited loop.")
Example 3: Retry Logic
import random
max_retries = 5
retries = 0
while True:
# Simulate an operation that may fail
success = random.choice([True, False])
if success:
print("Operation succeeded!")
break
else:
print("Operation failed, retrying...")
retries += 1
if retries >= max_retries:
print("Max retries reached. Exiting...")
break
Example 4: Real-time Data Processing
import random
import time
print("Starting data processing...")
while True:
# Simulate real-time data stream
data = random.randint(1, 100)
print(f"Processing data: {data}")
time.sleep(1) # Simulate a delay in data arrival
if data > 90: # Example condition to exit the loop
print("Condition met, stopping data processing.")
break
print("Data processing stopped.")
The while True
loop is a powerful construct in Python for creating loops that should run indefinitely until a specific condition is met. By using break
statements and conditions within the loop, you can control when to exit the loop, making it suitable for a wide range of applications such as interactive menus, event waiting, retry logic, and real-time data processing.
Examples of Python loops
Sure, let’s dive into some complex examples of Python loops to better understand control structures.
1. Prime Number Checker with Nested Loops
# This program finds all prime numbers up to a given limit
limit = 100
primes = []
for num in range(2, limit + 1): # Check each number from 2 to limit
is_prime = True
for i in range(2, int(num**0.5) + 1): # Check divisors from 2 to sqrt(num)
if num % i == 0: # If num is divisible by i, it is not prime
is_prime = False
break # No need to check further, exit inner loop
if is_prime:
primes.append(num) # Add prime number to list
print(f"Prime numbers up to {limit}: {primes}")
2. Fibonacci Sequence Generator
# Generate Fibonacci sequence up to a certain number of terms
n_terms = 10
a, b = 0, 1
fibonacci_sequence = [a, b]
for _ in range(n_terms - 2): # We already have the first two terms
a, b = b, a + b
fibonacci_sequence.append(b)
print(f"Fibonacci sequence with {n_terms} terms: {fibonacci_sequence}")
3. Matrix Multiplication
# Multiplying two matrices using nested loops
A = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
B = [
[9, 8, 7],
[6, 5, 4],
[3, 2, 1]
]
# Resultant matrix C will have dimensions of A's rows by B's columns
C = [[0 for _ in range(len(B[0]))] for _ in range(len(A))]
# Perform matrix multiplication
for i in range(len(A)): # Iterate through rows of A
for j in range(len(B[0])): # Iterate through columns of B
for k in range(len(B)): # Iterate through rows of B
C[i][j] += A[i][k] * B[k][j]
print("Result of matrix multiplication:")
for row in C:
print(row)
4. Pascal’s Triangle
# Print Pascal's Triangle up to a certain number of rows
n_rows = 5
triangle = []
for i in range(n_rows):
row = [1] # Each row starts with 1
if triangle: # If triangle is not empty
last_row = triangle[-1]
row.extend([last_row[j] + last_row[j + 1] for j in range(len(last_row) - 1)])
row.append(1) # Each row ends with 1
triangle.append(row)
print("Pascal's Triangle:")
for row in triangle:
print(row)
5. Sudoku Solver Using Backtracking
# Solves a Sudoku puzzle using backtracking
def print_board(board):
for row in board:
print(row)
def is_valid(board, row, col, num):
for i in range(9):
if board[row][i] == num or board[i][col] == num:
return False
start_row, start_col = 3 * (row // 3), 3 * (col // 3)
for i in range(start_row, start_row + 3):
for j in range(start_col, start_col + 3):
if board[i][j] == num:
return False
return True
def solve_sudoku(board):
for row in range(9):
for col in range(9):
if board[row][col] == 0:
for num in range(1, 10):
if is_valid(board, row, col, num):
board[row][col] = num
if solve_sudoku(board):
return True
board[row][col] = 0 # Backtrack
return False
return True
# Example Sudoku board (0 represents empty cells)
board = [
[5, 3, 0, 0, 7, 0, 0, 0, 0],
[6, 0, 0, 1, 9, 5, 0, 0, 0],
[0, 9, 8, 0, 0, 0, 0, 6, 0],
[8, 0, 0, 0, 6, 0, 0, 0, 3],
[4, 0, 0, 8, 0, 3, 0, 0, 1],
[7, 0, 0, 0, 2, 0, 0, 0, 6],
[0, 6, 0, 0, 0, 0, 2, 8, 0],
[0, 0, 0, 4, 1, 9, 0, 0, 5],
[0, 0, 0, 0, 8, 0, 0, 7, 9]
]
if solve_sudoku(board):
print("Solved Sudoku board:")
print_board(board)
else:
print("No solution exists")
6. Flatten a Nested List
# Flatten a nested list using recursion
def flatten(nested_list):
flat_list = []
for element in nested_list:
if isinstance(element, list):
flat_list.extend(flatten(element))
else:
flat_list.append(element)
return flat_list
nested_list = [1, [2, [3, 4], 5], 6, [7, 8, [9, 10]]]
flattened_list = flatten(nested_list)
print(f"Flattened list: {flattened_list}")
Tricky Questions for Interview:
Question1:
The approach if 60 <= a < 80:
is more performance efficient in Python. This is because of the way Python handles chained comparisons and the reduced number of operations involved.
Comparison of the Two Approaches
if a < 80 and a >= 60:
:- This approach involves two separate comparisons and a logical
and
operation. - It first checks if
a < 80
and then checks ifa >= 60
. Both conditions need to be evaluated separately.
- This approach involves two separate comparisons and a logical
if 60 <= a < 80:
:- This approach leverages Python’s support for chaining comparisons.
- The expression
60 <= a < 80
is equivalent to(60 <= a) and (a < 80)
, but it is evaluated more efficiently. - Python checks
60 <= a
, and if true, it then checksa < 80
in a single step.
Why Chained Comparisons are More Efficient
- Single Step Evaluation: In
if 60 <= a < 80:
, Python performs the comparison in a single step, checkinga
against both bounds without the need for an additional logical operation. - Short-circuiting: If
a
is less than 60, Python immediately knows the entire condition is false without checkinga < 80
, making it slightly faster in some cases.
Example and Performance Check
Here’s an example to illustrate both approaches and a simple performance check using timeit
:
import timeit
# Define a sample value
a = 70
# Approach 1
def approach1(a):
if a < 80 and a >= 60:
return True
return False
# Approach 2
def approach2(a):
if 60 <= a < 80:
return True
return False
# Timeit setup
setup = "a = 70"
stmt1 = "approach1(a)"
stmt2 = "approach2(a)"
# Timing the approaches
time1 = timeit.timeit(stmt=stmt1, setup="from __main__ import approach1, a", number=1000000)
time2 = timeit.timeit(stmt=stmt2, setup="from __main__ import approach2, a", number=1000000)
print(f"Approach 1 time: {time1}")
print(f"Approach 2 time: {time2}")
Running this code would show that approach2
(the chained comparison) is slightly faster than approach1
.
Leave a Reply