๐ ๐ฅ While Loops in Python: TikTok Reels Style#
โWhile loops are like TikTok reelsโlooping endlessly until you swipe away (or meet the condition to stop).โ
On TikTok, reels keep playing one after another, looping endlessly unless you take actionโlike swiping to the next video, closing the app, or running out of content. Similarly, while loops in Python repeat a block of code until a condition is no longer true.
Letโs break this down TikTok-style and explore how while loops work in Python. ๐ถโจ
๐ฏ What is a While Loop?#
A while loop in Python is like the TikTok algorithm:
It keeps showing you reels as long as youโre active (the condition is true).
The moment you swipe away or close the app (the condition becomes false), the loop stops.
Syntax
A while loop in Python has the following syntax:
while condition:
# code block
The
condition
is a Boolean expression that evaluates toTrue
orFalse
.The code block inside the loop is executed as long as the
condition
isTrue
.The code must be indented to indicate that itโs part of the loop.
๐ฌ Example 1: Watching Reels Until You Swipe Away#
Letโs simulate watching TikTok reels. As long as youโre enjoying the content, the loop continues:
enjoying_reels = True
reel_count = 0
while enjoying_reels:
reel_count += 1
print(f"Watching reel #{reel_count}... ๐ฅ")
if reel_count == 5: # After 5 reels, you get bored
print("I'm bored. Swiping away... ๐")
enjoying_reels = False
Watching reel #1... ๐ฅ
Watching reel #2... ๐ฅ
Watching reel #3... ๐ฅ
Watching reel #4... ๐ฅ
Watching reel #5... ๐ฅ
I'm bored. Swiping away... ๐
๐ฏ Key Idea: The loop keeps running while the condition enjoying_reels
is True
. Once it becomes False
, the loop stops.
โณ Infinite Loops: The Never-Ending TikTok Scrolling#
What happens if you never get bored? Thatโs an infinite loopโlike getting trapped in endless TikTok reels because the condition never changes.
Example 2: Infinite Reels#
import time
while True: # This condition is always True
print("Another reel... ๐ถ")
time.sleep(1) # Add a delay for realism (optional)
โ ๏ธ Warning: Infinite loops will keep running forever unless you manually stop them. Always make sure your loop has a way to exit!
๐ญ Adding a Swipe Condition with User Input#
Letโs introduce interactivity: You can swipe away whenever you want, like on TikTok.
Example 3: Interactive Reels#
reel_count = 0
while True:
reel_count += 1
print(f"Watching reel #{reel_count}... ๐ฅ")
user_input = input("Swipe to the next reel? (yes/no): ")
if user_input.lower() == "no":
print("Swiping away. Goodbye, TikTok! ๐")
break
Watching reel #1... ๐ฅ
---------------------------------------------------------------------------
StdinNotImplementedError Traceback (most recent call last)
Cell In[2], line 6
4 reel_count += 1
5 print(f"Watching reel #{reel_count}... ๐ฅ")
----> 6 user_input = input("Swipe to the next reel? (yes/no): ")
8 if user_input.lower() == "no":
9 print("Swiping away. Goodbye, TikTok! ๐")
File ~/drexel_runner_engineering/actions-runner/_work/_tool/Python/3.11.11/x64/lib/python3.11/site-packages/ipykernel/kernelbase.py:1281, in Kernel.raw_input(self, prompt)
1279 if not self._allow_stdin:
1280 msg = "raw_input was called, but this frontend does not support input requests."
-> 1281 raise StdinNotImplementedError(msg)
1282 return self._input_request(
1283 str(prompt),
1284 self._parent_ident["shell"],
1285 self.get_parent("shell"),
1286 password=False,
1287 )
StdinNotImplementedError: raw_input was called, but this frontend does not support input requests.
๐ฏ Key Idea: Use break
to exit the loop when the user decides to stop watching reels.
๐ต Skipping Over Content with continue
#
Sometimes, you want to skip certain reels (e.g., boring or irrelevant ones) but keep watching the rest. The continue
statement skips the current iteration and moves to the next reel.
Example 4: Skipping Boring Reels#
reels = [
"Funny Reel ๐",
"Ad Reel ๐",
"Dance Reel ๐",
"Boring Reel ๐",
"Pet Reel ๐ถ",
]
for reel in reels:
if "Boring" in reel:
print(f"Skipping {reel}... ๐ด")
continue
print(f"Watching {reel}... ๐ฅ")
๐ฏ Key Idea: continue
skips the current iteration without stopping the loop entirely.
๐ก Nested While Loops: Reels Within Reels#
TikTok might loop through different categories of content (e.g., funny, dance, pet reels). You can use nested loops to simulate categories within categories.
Example 5: Watching Content by Category#
categories = {
"Funny": ["Reel 1 ๐", "Reel 2 ๐"],
"Dance": ["Reel 1 ๐", "Reel 2 ๐"],
"Pets": ["Reel 1 ๐ถ", "Reel 2 ๐ฑ"],
}
for category, reels in categories.items():
print(f"Category: {category} ๐")
for reel in reels:
print(f" Watching {reel} ๐ฅ")
๐ฏ Key Idea: Nested loops let you handle complex structures like categories or playlists.
๐ ๏ธ Controlling Loops with Counters#
Letโs limit how many reels you can watch before TikTok automatically stops (like a parental control or time limit).
Example 6: TikTok Timeout#
time_limit = 3 # Max number of reels you can watch
reel_count = 0
while reel_count < time_limit:
reel_count += 1
print(f"Watching reel #{reel_count}... ๐ฅ")
else:
print("You've reached your time limit! No more TikTok for now. ๐ซ")
๐ฏ Key Idea: Use a counter to keep track of iterations and combine it with the else
block for graceful exits.
๐ฌ Conclusion: While Loops in TikTok Style#
Just like TikTok reels, while loops repeat endlessly until you break the flow. Whether youโre interacting with user input, skipping boring items, or timing out the session, while
loops offer dynamic control for repetitive tasks.
๐ Key Takeaways:#
while condition:
: The loop runs as long as the condition is true.Infinite Loops: Great for continuous processes (but be cautious!).
break
: Exit the loop early when a specific condition is met.continue
: Skip over the current iteration and move to the next.Counters and Conditions: Use counters to limit or manage iterations.
Nested Loops: Perfect for organizing complex structures like categories or playlists.
With this knowledge, you can handle loops like a proโwhether youโre programming TikTok reels or any other repetitive process! ๐ฅโจ