0% found this document useful (0 votes)
26 views13 pages

2.b Only While Loop

The document contains multiple examples of using while loops in Python, demonstrating various functionalities such as user input, conditional statements, and iterations. Examples include basic loops, countdown timers, games, and calculators, showcasing how to implement logic for tasks like summing numbers, finding prime numbers, and creating a simple voting system. Each example is structured to illustrate specific programming concepts effectively.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
26 views13 pages

2.b Only While Loop

The document contains multiple examples of using while loops in Python, demonstrating various functionalities such as user input, conditional statements, and iterations. Examples include basic loops, countdown timers, games, and calculators, showcasing how to implement logic for tasks like summing numbers, finding prime numbers, and creating a simple voting system. Each example is structured to illustrate specific programming concepts effectively.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 13

telugu_dialogues = ["Fire, kadhu, Wildfire, Hlo - Pushpa"]

index = 0
while index < len(telugu_dialogues):
print("Dialogue:", telugu_dialogues[index])
index += 1
:::::::::::::::::::::::::::::::::::::::::::::
Example 1: Basic While Loop

count = 1

while count <= 5:


print(count)
count += 1 # Increment the count by 1

:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::

Example 2: While Loop with User Input

user_input = ""

while user_input.lower() != "exit":


user_input = input("Type 'exit' to quit: ")
print("You typed:", user_input)

::::::::::::::::::::::::::::::::::::::::::::::::::::

Example 3: Using break in a While Loop

count = 0

while True: # Infinite loop


count += 1
print(count)
if count >= 5:
break # Exit the loop when count reaches 5

::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::

Example 4: Using continue in a While Loop

count = 0

while count < 10:


count += 1
if count % 2 == 0:
continue # Skip even numbers
print(count) # Print only odd numbers

::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::

Example 5: While Loop with a List

fruits = ["apple", "banana", "cherry"]


index = 0

while index < len(fruits):


print(fruits[index])
index += 1 # Move to the next index
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::

Example 6: Countdown Timer

import time

countdown = 5

while countdown > 0:


print(countdown)
countdown -= 1 # Decrement the countdown
time.sleep(1) # Wait for 1 second

print("Time's up!")

::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::

Example 7: Summing Numbers Until a Condition is Met

total = 0

while True:
number = float(input("Enter a number (negative to quit): "))
if number < 0:
break # Exit the loop if the number is negative
total += number # Add the number to the total

print("Total sum:", total)

:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::

Example 8: Guessing Game

import random

secret_number = random.randint(1, 10) # Random number between 1 and 10


guess = None

while guess != secret_number:


guess = int(input("Guess the number (1-10): "))
if guess < secret_number:
print("Too low! Try again.")
elif guess > secret_number:
print("Too high! Try again.")

print("Congratulations! You've guessed the number:", secret_number)

::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::

Example 9: Fibonacci Sequence

limit = 100
a, b = 0, 1

print("Fibonacci sequence up to", limit, ":")


while a < limit:
print(a, end=" ")
a, b = b, a + b # Update values for the next Fibonacci number
:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::

Example 10: Infinite Loop with Exit Condition

while True:
command = input("Enter 'stop' to exit the loop: ")
if command.lower() == 'stop':
print("Exiting the loop.")
break
else:
print("You entered:", command)

:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::

Example 11: Counting Down with a Step

start = 10
step = 2

while start >= 0:


print(start)
start -= step # Decrement by the specified step

:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::

Example 12: Validating User Input

while True:
user_input = input("Enter a positive integer: ")
if user_input.isdigit() and int(user_input) > 0:
print("You entered a valid positive integer:", user_input)
break # Exit the loop if the input is valid
else:
print("Invalid input. Please try again.")

:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::

Example 13: Reversing a String

user_string = input("Enter a string to reverse: ")


reversed_string = ""
index = len(user_string) - 1

while index >= 0:


reversed_string += user_string[index]
index -= 1 # Move to the previous character

print("Reversed string:", reversed_string)

:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::

Example 14: Collatz Conjecture


This example implements the Collatz conjecture, which states that for any positive
integer ( n ):

If ( n ) is even, divide it by 2.
If ( n ) is odd, multiply it by 3 and add 1.
Repeat the process until ( n ) becomes 1.

n = int(input("Enter a positive integer: "))

while n != 1:
print(n, end=" ")
if n % 2 == 0:
n //= 2 # If n is even
else:
n = 3 * n + 1 # If n is odd

print(1) # Print the last number (1)

::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::

Example 15: Counting Vowels in a String

user_string = input("Enter a string: ")


vowels = "aeiouAEIOU"
count = 0
index = 0

while index < len(user_string):


if user_string[index] in vowels:
count += 1
index += 1 # Move to the next character

print("Number of vowels in the string:", count)

:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::

Example 16: Factorial Calculation

number = int(input("Enter a positive integer to calculate its factorial: "))


factorial = 1
count = 1

while count <= number:


factorial *= count # Multiply the current count to the factorial
count += 1 # Increment the count

print(f"The factorial of {number} is {factorial}.")

::::::::::::::::::::::::::::::::::::::::::::::::::::::::

Example 17: Palindrome Checker

user_string = input("Enter a string: ")


reversed_string = ""
index = len(user_string) - 1

while index >= 0:


reversed_string += user_string[index]
index -= 1

if user_string == reversed_string:
print(f"{user_string} is a palindrome.")
else:
print(f"{user_string} is not a palindrome.")
:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::

Example 19: Finding the Largest Number

largest = None

while True:
number = float(input("Enter a number (negative to quit): "))
if number < 0:
break # Exit the loop if the number is negative
if largest is None or number > largest:
largest = number # Update largest if the current number is greater

if largest is not None:


print("The largest number entered is:", largest)
else:
print("No positive numbers were entered.")

::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::

Example 20: Simple ATM Simulation

balance = 1000 # Initial balance

while True:
print("\nATM Menu:")
print("1. Check Balance")
print("2. Deposit Money")
print("3. Withdraw Money")
print("4. Exit")

choice = input("Choose an option (1-4): ")

if choice == '1':
print("Your balance is:", balance)
elif choice == '2':
deposit = float(input("Enter amount to deposit: "))
balance += deposit
print("Deposit successful! New balance:", balance)
elif choice == '3':
withdraw = float(input("Enter amount to withdraw: "))
if withdraw > balance:
print("Insufficient funds!")
else:
balance -= withdraw
print("Withdrawal successful! New balance:", balance)
elif choice == '4':
print("Thank you for using the ATM. Goodbye!")
break
else:
print("Invalid choice. Please try again.")

::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::

Example 21: Repeatedly Asking for a Password

correct_password = "secret123"
attempts = 0

while attempts < 3:


password = input("Enter the password: ")
if password == correct_password:
print("Access granted!")
break
else:
print("Incorrect password. Try again.")
attempts += 1

if attempts == 3:
print("Too many failed attempts. Access denied.")

:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::

Example 22: Multiplication Table

number = int(input("Enter a number to generate its multiplication table: "))


count = 1

while count <= 10:


print(f"{number} x {count} = {number * count}")
count += 1 # Increment the count

::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::

Example 26: Simple Text-Based Adventure Game

print("Welcome to the Adventure Game!")


print("You are in a forest. You can go 'left' or 'right'.")

while True:
choice = input("Which way do you want to go? (left/right): ").lower()

if choice == 'left':
print("You encounter a friendly dragon! You win!")
break
elif choice == 'right':
print("You fall into a pit! Game over.")
break
else:
print("Invalid choice. Please choose 'left' or 'right'.")

::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::

Example 28: Simple Calculator

while True:
print("\nSimple Calculator")
print("1. Add")
print("2. Subtract")
print("3. Multiply")
print("4. Divide")
print("5. Exit")

choice = input("Choose an operation (1-5): ")


if choice == '5':
print("Exiting the calculator. Goodbye!")
break

num1 = float(input("Enter first number: "))


num2 = float(input("Enter second number: "))

if choice == '1':
print(f"{num1} + {num2} = {num1 + num2}")
elif choice == '2':
print(f"{num1} - {num2} = {num1 - num2}")
elif choice == '3':
print(f"{num1} * {num2} = {num1 * num2}")
elif choice == '4':
if num2 != 0:
print(f"{num1} / {num2} = {num1 / num2}")
else:
print("Error: Division by zero!")
else:
print("Invalid choice. Please try again.")

::::::::::::::::::::::::::::::::::::::::::::::::::::::::::

Example 29: Finding Prime Numbers

limit = int(input("Enter a limit to find prime numbers: "))


number = 2 # Start checking for prime numbers from 2

while number <= limit:


is_prime = True
for i in range(2, int(number**0.5) + 1):
if number % i == 0:
is_prime = False
break
if is_prime:
print(number)
number += 1
:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::

Example 30: Repeatedly Asking for a Username

while True:
username = input("Enter a username (cannot be empty): ")
if username:
print("Username accepted:", username)
break # Exit the loop if the username is valid
else:
print("Invalid username. Please try again.")

::::::::::::::::::::::::::::::::::::::::::::::::::::::::

Example 31: Simple Voting System (continued)

votes = {"A": 0, "B": 0, "C": 0}

while True:
print("\nCandidates:")
for candidate in votes:
print(candidate)

choice = input("Vote for a candidate (or type 'exit' to finish voting):


").capitalize()

if choice == 'exit':
break

if choice in votes:
votes[choice] += 1
print(f"Thank you for voting for {choice}!")
else:
print("Invalid candidate. Please try again.")

print("\nVoting results:")
for candidate, count in votes.items():
print(f"{candidate}: {count} votes")

:::::::::::::::::::::::::::::::::::::::::::::::::::::;

Example 32: Simple Text-Based Quiz

score = 0

while True:
print("\nQuiz Time!")
print("1. What is the capital of France?")
print("2. What is 2 + 2?")
print("3. What is the color of the sky?")
print("4. Exit")

choice = input("Choose a question (1-4): ")

if choice == '1':
answer = input("Your answer: ")
if answer.lower() == "paris":
print("Correct!")
score += 1
else:
print("Wrong! The correct answer is Paris.")
elif choice == '2':
answer = input("Your answer: ")
if answer == "4":
print("Correct!")
score += 1
else:
print("Wrong! The correct answer is 4.")
elif choice == '3':
answer = input("Your answer: ")
if answer.lower() == "blue":
print("Correct!")
score += 1
else:
print("Wrong! The correct answer is blue.")
elif choice == '4':
print("Exiting the quiz. Your score is:", score)
break
else:
print("Invalid choice. Please try again.")

::::::::::::::::::::::::::::::::::::::::::::::::::::::::::

Example 33: Simple Password Strength Checker

while True:
password = input("Enter a password (or type 'exit' to quit): ")

if password.lower() == 'exit':
break # Exit the loop if the user types 'exit'

if len(password) < 8:
print("Password is too short. It must be at least 8 characters.")
elif not any(char.isdigit() for char in password):
print("Password must contain at least one digit.")
elif not any(char.isalpha() for char in password):
print("Password must contain at least one letter.")
else:
print("Password is strong!")

::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::

Example 34: Simple Currency Converter

exchange_rate = 1.2 # Example: 1 USD = 1.2 EUR

while True:
amount = input("Enter amount in USD to convert to EUR (or type 'exit' to quit):
")

if amount.lower() == 'exit':
break # Exit the loop if the user types 'exit'

try:
amount = float(amount)
converted_amount = amount * exchange_rate
print(f"{amount} USD is equal to {converted_amount:.2f} EUR.")
except ValueError:
print("Invalid amount. Please enter a numeric value.")

::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::

Example 35: Simple Rock-Paper-Scissors Game

import random

choices = ["rock", "paper", "scissors"]

while True:
user_choice = input("Enter rock, paper, or scissors (or type 'exit' to quit):
").lower()

if user_choice == 'exit':
break # Exit the loop if the user types 'exit'

if user_choice not in choices:


print("Invalid choice. Please try again.")
continue # Skip to the next iteration if the choice is invalid

computer_choice = random.choice(choices)
print("Computer chose:", computer_choice)

if user_choice == computer_choice:
print("It's a tie!")
elif (user_choice == "rock" and computer_choice == "scissors") or \
(user_choice == "paper" and computer_choice == "rock") or \
(user_choice == "scissors" and computer_choice == "paper"):
print("You win!")
else:
print("You lose!")

::::::::::::::::::::::::::::::::::::::::::::::::::::::::

Example 36: Simple To-Do List

todo_list = []

while True:
print("\nTo-Do List:")
for index, item in enumerate(todo_list, start=1):
print(f"{index}. {item}")

print("\nOptions:")
print("1. Add a task")
print("2. Remove a task")
print("3. Exit")

choice = input("Choose an option (1-3): ")

if choice == '1':
task = input("Enter the task to add: ")
todo_list.append(task)
print(f"Task '{task}' added.")
elif choice == '2':
task_number = int(input("Enter the task number to remove: "))
if 1 <= task_number <= len(todo_list):
removed_task = todo_list.pop(task_number - 1)
print(f"Task '{removed_task}' removed.")
else:
print("Invalid task number.")
elif choice == '3':
print("Exiting the to-do list. Goodbye!")
break
else:
print("Invalid choice. Please try again.")

:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::

Example 38: Simple Interest Calculator

while True:
principal = input("Enter the principal amount (or type 'exit' to quit): ")

if principal.lower() == 'exit':
break # Exit the loop if the user types 'exit'
rate = float(input("Enter the rate of interest (in %): "))
time = float(input("Enter the time (in years): "))

try:
principal = float(principal)
simple_interest = (principal * rate * time) / 100
print(f"The simple interest is: {simple_interest:.2f}")
except ValueError:
print("Invalid input. Please enter numeric values.")

:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::

Example 39: Simple Temperature Converter

while True:
print("\nTemperature Converter")
print("1. Celsius to Fahrenheit")
print("2. Fahrenheit to Celsius")
print("3. Exit")

choice = input("Choose an option (1-3): ")

if choice == '3':
print("Exiting the converter. Goodbye!")
break

if choice == '1':
celsius = float(input("Enter temperature in Celsius: "))
fahrenheit = (celsius * 9/5) + 32
print(f"{celsius}°C is equal to {fahrenheit:.2f}°F.")
elif choice == '2':
fahrenheit = float(input("Enter temperature in Fahrenheit: "))
celsius = (fahrenheit - 32) * 5/9
print(f"{fahrenheit}°F is equal to {celsius:.2f}°C.")
else:
print("Invalid choice. Please try again.")

::::::::::::::::::::::::::::::::::::::::::::::::::::::::

Example 40: Simple Email Validator (continued)

import re

while True:
email = input("Enter an email address (or type 'exit' to quit): ")

if email.lower() == 'exit':
break # Exit the loop if the user types 'exit'

# Basic email validation using regex


if re.match(r"[^@]+@[^@]+\.[^@]+", email):
print(f"{email} is a valid email address.")
else:
print(f"{email} is not a valid email address. Please try again.")

::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::

Example 41: Simple Number Reversal


while True:
number = input("Enter a number to reverse (or type 'exit' to quit): ")

if number.lower() == 'exit':
break # Exit the loop if the user types 'exit'

reversed_number = number[::-1] # Reverse the string representation of the


number
print(f"The reversed number is: {reversed_number}")

::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::

Example 42: Simple String Counter

while True:
user_string = input("Enter a string (or type 'exit' to quit): ")

if user_string.lower() == 'exit':
break # Exit the loop if the user types 'exit'

char_to_count = input("Enter the character to count: ")

count = 0
index = 0

while index < len(user_string):


if user_string[index] == char_to_count:
count += 1
index += 1 # Move to the next character

print(f"The character '{char_to_count}' occurs {count} times in the string.")

:::::::::::::::::::::::::::::::::::::::::::::::::::::::

Example 44: Simple Binary to Decimal Converter

while True:
binary_str = input("Enter a binary number (or type 'exit' to quit): ")

if binary_str.lower() == 'exit':
break # Exit the loop if the user types 'exit'

decimal_value = 0
index = 0

while index < len(binary_str):


if binary_str[-(index + 1)] == '1':
decimal_value += 2 ** index
index += 1

print(f"The decimal value of binary {binary_str} is: {decimal_value}")

::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::

Example 45: Simple Character Frequency Counter

while True:
user_string = input("Enter a string (or type 'exit' to quit): ")
if user_string.lower() == 'exit':
break # Exit the loop if the user types 'exit'

frequency = {}

index = 0
while index < len(user_string):
char = user_string[index]
if char in frequency:
frequency[char] += 1
else:
frequency[char] = 1
index += 1

print("Character frequencies:")
for char, count in frequency.items():
print(f"'{char}': {count}")

:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::

You might also like