Example 1: Guessing Game

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 as guess_count is less than guess_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 potential ValueError 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

  1. Interactive Menus: Continuously display a menu until the user chooses to exit.
  2. Waiting for Events: Wait for an external event or condition to occur.
  3. Retry Logic: Retry an operation until it succeeds or until a maximum number of retries is reached.
  4. 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:

Q.Which approach is more performance efficient in Python?
a.if a < 80 and a >= 60
b.if 60 <= a < 80
c.Both are Same

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

  1. 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 if a >= 60. Both conditions need to be evaluated separately.
  2. 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 checks a < 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, checking a 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 checking a < 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.


Discover more from HintsToday

Subscribe to get the latest posts sent to your email.

Pages ( 3 of 3 ): « Previous12 3

Discover more from HintsToday

Subscribe now to keep reading and get access to the full archive.

Continue reading