0% found this document useful (0 votes)
4 views3 pages

While Loop

The document explains the use of while loops in Python, detailing their structure and providing multiple examples, including basic loops, infinite loops, and the use of break and continue statements. It also includes practical programs that demonstrate calculating sums, reversing numbers and strings, finding the largest digit, and handling user input with a PIN verification system. Overall, it serves as a comprehensive guide to understanding and implementing while loops in Python.

Uploaded by

rsingh.csed.cf
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views3 pages

While Loop

The document explains the use of while loops in Python, detailing their structure and providing multiple examples, including basic loops, infinite loops, and the use of break and continue statements. It also includes practical programs that demonstrate calculating sums, reversing numbers and strings, finding the largest digit, and handling user input with a PIN verification system. Overall, it serves as a comprehensive guide to understanding and implementing while loops in Python.

Uploaded by

rsingh.csed.cf
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

In Python, a while loop repeatedly executes a block of code as long as a given condition is True.

The loop
continues until the condition becomes False. It is useful when you do not know beforehand how many iterations
you need, but you want to keep executing until a certain condition is met.

while <condition>:
# code to execute as long as the condition is True

Example 1: Basic while loop


count = 0
while count < 5:
print(count)
count += 1 # Increment count to eventually stop the loop

Example 2: Infinite while loop (dangerous, but useful in some cases)

while True:
print("This will run forever unless you stop it!")

Example 3: Using break to exit a loop


count = 0
while True: # Infinite loop
print(count)
count += 1
if count == 5:
break # Exit the loop when count reaches 5
Example 4: Using continue to skip an iteration
​ count = 0
while count < 5:
​​ count += 1
​​ if count == 3:
​ ​ continue # Skip the rest of the loop when count is 3
​​ print(count)

Example 5: While loop with user input


while True:
user_input = input("Enter 'yes' to continue or 'no' to exit: ")
if user_input == 'no':
print("Exiting the loop.")
break
elif user_input == 'yes':
print("Continuing the loop.")
else:
print("Invalid input. Please try again.")
Write a program that calculates the sum of all numbers from 1 to a given number n (use input to get n)
# Get input from the user
n = int(input("Enter a number: "))

# Initialize variables
sum_of_numbers = 0
i=1

# Use a while loop to calculate the sum


while i <= n:
sum_of_numbers += i
i += 1
# Display the result
print("The sum of all numbers from 1 to", n, "is:", sum_of_numbers)

Write a program that reverses a given number using a while loop. For example, input is 12345, output 54321.

# Get input from the user


number = int(input("Enter a number: "))
# Initialize a variable to store the reversed number
reversed_number = 0
# Use a while loop to reverse the number
while number > 0:
# Get the last digit of the number
last_digit = number % 10
# Add the last digit to the reversed number
reversed_number = reversed_number * 10 + last_digit
# Remove the last digit from the original number
number = number // 10

# Display the reversed number


print("Reversed number:", reversed_number)

Write a program that finds the largest digit in a given number using a while loop.
# Get input from the user
number = int(input("Enter a number: "))

# Initialize a variable to store the largest digit


largest_digit = 0
# Use a while loop to find the largest digit
while number > 0:
# Get the last digit of the number
last_digit = number % 10

# Update the largest digit if the last digit is greater


if last_digit > largest_digit:
largest_digit = last_digit

# Remove the last digit from the number


number = number // 10

# Display the largest digit


print("The largest digit is:", largest_digit)
Python program that reverses a string entered by the user using a while loop:
# Get input from the user
user_string = input("Enter a string: ")

# Initialize an empty string to store the reversed string


reversed_string = ""

# Initialize an index variable to the last index of the string


index = len(user_string) - 1

# Use a while loop to reverse the string


while index >= 0:
# Add the character at the current index to the reversed string
reversed_string += user_string[index]
# Move to the previous character
index -= 1

# Display the reversed string


print("Reversed string:", reversed_string)

Python program that allows the user three attempts to enter the correct PIN. If the user enters the incorrect PIN
three times, the program will exit.
# Set the correct PIN
correct_pin = "1234"

# Initialize the number of attempts


attempts = 0
max_attempts = 3

# Start the loop to allow up to 3 attempts


while attempts < max_attempts:
# Ask the user to input their PIN
user_pin = input("Enter your PIN: ")

# Check if the entered PIN is correct


if user_pin == correct_pin:
print("PIN correct! Access granted.")
break # Exit the loop if the PIN is correct
else:
attempts += 1 # Increment the attempt count
print(f"Incorrect PIN. You have {max_attempts - attempts} attempts remaining.")

# If all attempts are exhausted, exit message


if attempts == max_attempts:
print("Incorrect PIN entered 3 times. Access denied.")

You might also like