While Loops in Python
This presentation will explore the concept of while loops in Python, a
fundamental programming construct used for repetitive tasks. We'll delve
into the syntax, real-world applications, and practical examples to help
you understand and master this essential tool.
by Techno Skills
Understanding While Loops
What is a Loop?
A loop is a programming construct that allows a block of code to execute repeatedly until a condition is met.
What is a While Loop?
A while loop executes a block of code as long as a specified condition is True.
Syntax and Example
Syntax Example
while condition: count = 1
# Code to execute while count <= 5:
print("Hello, Python!")
count += 1
Real-Life Use Cases
1 User Authentication 2 Game Development 3 ATM Machine
Continuously asking for a Keeping a game running until a Processing transactions until the
password until it's correct. player quits. user exits.
4 Web Scraping 5 Downloading Files
Extracting data from a website until there's nothing left. Retrying a download until it's complete.
Examples of While Loops
Print Numbers from 1 to 10 Sum of First 10 Natural Numbers
num = 1 num = 1
while num <= 10: sum = 0
print(num) while num <= 10:
num += 1 sum += num
num += 1
print("Sum:", sum)
Reverse Counting from 10 to 1 Keep Asking for Input Until Correct
num = 10 password = "Python123"
while num >= 1: user_input = ""
print(num)
num -= 1 while user_input != password:
user_input = input("Enter password: ")
print("Access Granted!")
4. Difference Between For and While Loop
Feature For Loop While Loop
Used for Iterating over sequences Repeating until a condition is false
Condition Uses a sequence like range() Uses a boolean condition
Example for i in range(5): while i < 5:
Break and Continue
Statements
break immediately exits the loop. continue skips the current iteration
and proceeds to the next.
Break (Exit the loop) Continue (Skip an
iteration)
num = 1
while num <= 10: num = 0
if num == 5: while num < 10:
break num += 1
print(num) if num % 2 == 0:
num += 1 continue
print(num)
Output:
Output:
1
2 1
3 3
4 5
7
9
10 Questions for While Loop Practice
1. Write a program to print numbers from 1 to 20 using a while loop.
2. Print only even numbers between 1 and 20 using a while loop.
3. Reverse print numbers from 100 to 50 using a while loop.
4. Take user input and keep asking until they enter a positive number.
5. Find the sum of digits of a number using a while loop.
6. Print the multiplication table of a given number using a while loop.
7. Write a program to count the number of digits in an integer using a while loop.
8. Reverse a given number using a while loop.
9. Check if a number is palindrome using a while loop.
10. Find the factorial of a number using a while loop.
Here9s a comparison table showing the
differences between List, Tuple, and
Dictionary in Python:
Feature List Tuple Dictionary
Definition Ordered, mutable Ordered, immutable Unordered collection of
collection of elements collection of elements key-value pairs
Syntax list = [1, 2, 3] tuple = (1, 2, 3) dict = {"name": "John",
"age": 25}
Mutable (Can be ' Yes o No Yes
changed?)
Indexing Yes (0-based index) Yes (0-based index) Yes (by key)
Duplicates Allowed? Yes Yes o No (Keys must be
unique)
Heterogeneous? (Can Yes Yes Yes
contain different data
types?)
Iterability Yes (Can be iterated Yes Yes
using loops)
Speed Slower than tuples Faster than lists Depends on key lookup
Use Case When you need a When you need a fixed When you need key-value
modifiable collection collection pairs
Methods .append(), .remove(), .sort(), .count(), .index() .keys(), .values(), .items(),
etc. etc.
List , Tuple , Dict Code example
Code '
# List
my_list = [1, 2, 3]
my_list.append(4) #allowed mutable
#Allowed (mutable)# Tuple
my_tuple = (1, 2, 3)
#my_tuple[0] = 4 # Not allowed (immutable)
# Dictionary
my_dict = {"name": "Alice", "age": 25}
my_dict["city"] = "New York
Conclusion
While loops are essential for coding interviews and real-world
applications. They provide a powerful way to handle repetitive tasks and
solve complex problems. By understanding the syntax, use cases, and
examples, you can effectively utilize while loops in your Python
programming journey.