๐Ÿ“– ๐Ÿค– Loops in Python: Westworld Edition#

โ€œRepeating the same storylines until someone breaks the code (or the loop).โ€

In Python, loops are the programming equivalent of Westworldโ€™s hostsโ€”they repeat the same tasks over and over, like scripted storylines in the park. Whether itโ€™s reliving a day in Sweetwater or printing the same statement 100 times, loops execute a block of code until someone (you, the programmer) breaks the loop or stops the story.

Letโ€™s dive into the world of loops and learn how to control themโ€”just like the architects of Westworld! ๐Ÿš‚โœจ

๐ŸŽก What are Loops?#

Loops let you repeat a block of code multiple times without writing it manually. In Westworld terms, theyโ€™re like the hostsโ€™ programmed narrativesโ€”a repeating cycle of events that only changes if something disrupts the loop.

In Python, we have two main types of loops:

  1. for loops: Like a structured storyline, they know exactly how many times to repeat.

Syntax

for variable in iterable:
    # Code block to execute for each item in 'iterable'
  • variable: Represents the current item in the loop.

  • iterable: A collection of items to loop over.

all the code inside the loop should be indented.


Note

Definition An iterable is any Python object capable of returning its elements one at a time, allowing it to be looped over in a for loop or passed to functions like list() or sum().
Examples of iterables include sequences (list, tuple, dict, str) and objects implementing the iter() or getitem() method.

  1. while loops: Like an open-world narrative, they keep going until a specific condition changes.

Syntax

while condition:
    # Code block to execute until 'condition' is False
  • condition: A Boolean expression that determines when to stop the loop.

all the code inside the loop should be indented.


๐ŸŽญ The for Loop: The Structured Narrative#

A for loop is like a programmed storyline in Westworldโ€”predictable, pre-scripted, and designed to run a set number of times.

Example: Hosts Serving Drinks in Sweetwater#

for drink in ["Whiskey", "Gin", "Beer"]:
    print(f"Host serves {drink}")
Host serves Whiskey
Host serves Gin
Host serves Beer

Hereโ€™s what happens:

  1. The loop iterates over the list of drinks.

  1. Each iteration assigns a drink (e.g., โ€œWhiskeyโ€) to the variable drink.

  1. The host (the loop) serves the drink.

๐ŸŽฏ Key Idea: A for loop runs once for each item in a sequence (like a list or range). Itโ€™s predictable, just like Sweetwaterโ€™s daily events.

๐ŸŽข Iterating Over a Range of Numbers#

Letโ€™s simulate the hosts interacting with 5 guests:

for guest in range(1, 6):  # Numbers 1 to 5
    print(f"Host greets Guest #{guest}")
Host greets Guest #1
Host greets Guest #2
Host greets Guest #3
Host greets Guest #4
Host greets Guest #5

๐ŸŽฏ Key Idea: range(start, end) creates a sequence of numbers for the loop to iterate over. Itโ€™s like the host greeting a fixed number of guests at the park gates.

๐Ÿค– The while Loop: The Open-World Narrative#

A while loop is like Westworldโ€™s unstructured storylinesโ€”it keeps running until a specific condition changes, giving it a sense of freedom. But beware: without a way to stop, it can run forever (like a host stuck in a malfunctioning narrative ๐Ÿ˜ฑ).

Example: Hosts Working Until Guests Leave#

guests_in_park = 5

while guests_in_park > 0:
    print(f"Host assists a guest. {guests_in_park} guests remaining.")
    guests_in_park -= 1  # A guest leaves the park
Host assists a guest. 5 guests remaining.
Host assists a guest. 4 guests remaining.
Host assists a guest. 3 guests remaining.
Host assists a guest. 2 guests remaining.
Host assists a guest. 1 guests remaining.

๐ŸŽฏ Key Idea: The while loop keeps running as long as the condition (guests_in_park > 0) is true. It stops when the condition is false (no guests left).

โš ๏ธ Beware of Infinite Loops: Hosts Gone Rogue#

If you donโ€™t update the condition, the loop might run foreverโ€”like a rogue host endlessly repeating their tasks!

guests_in_park = 5
i = 0
while guests_in_park > 0:
    i += 1
    print(f"Host assists a guest. {guests_in_park} guests remaining.")
    # Oops! We forgot to update `guests_in_park`!

    if i == 100:
        break

This will keep printing the same message forever (or until you manually stop the program). We added a break statement to stop the loop when the number of guests reaches 100.

๐Ÿ’ก Pro Tip: Always make sure the condition in your while loop will eventually become False. Otherwise, youโ€™ll end up with an endless loopโ€”just like Westworldโ€™s glitches.

๐ŸŽฎ Breaking the Loop: Taking Control#

What happens when you need to break free from a loop early, like a host gaining consciousness? You can use the break statement to terminate a loop, even if its condition hasnโ€™t been met yet.

Example: Hosts Breaking the Cycle#

for guest in range(1, 6):
    if guest == 3:  # A rogue guest disrupts the loop
        print("Rogue guest detected! Stopping the loop.")
        break
    print(f"Host greets Guest #{guest}")
Host greets Guest #1
Host greets Guest #2
Rogue guest detected! Stopping the loop.

๐ŸŽฏ Key Idea: The break statement immediately stops the loop, no matter where it is in the sequence.

๐ŸŽญ Skipping Iterations: The continue Statement#

Sometimes, you donโ€™t want to stop the loop entirelyโ€”you just want to skip one iteration. Use the continue statement to jump to the next iteration.

Example: Hosts Ignoring VIPs#

for guest in range(1, 6):
    if guest == 3:  # Guest #3 is a VIP
        print("Skipping VIP Guest #3")
        continue
    print(f"Host assists Guest #{guest}")
Host assists Guest #1
Host assists Guest #2
Skipping VIP Guest #3
Host assists Guest #4
Host assists Guest #5

๐ŸŽฏ Key Idea: The continue statement skips the rest of the current iteration but doesnโ€™t stop the loop entirely.

๐ŸŽจ Nested Loops: Hosts Within Hosts#

Sometimes, you need loops inside loopsโ€”just like hosts interacting with other hosts in nested storylines.

Example: Sweetwater Hosts Serving Drinks to Tables#

for table in range(1, 4):  # 3 tables
    for guest in range(1, 3):  # 2 guests per table
        print(f"Host serves Guest #{guest} at Table #{table}")
Host serves Guest #1 at Table #1
Host serves Guest #2 at Table #1
Host serves Guest #1 at Table #2
Host serves Guest #2 at Table #2
Host serves Guest #1 at Table #3
Host serves Guest #2 at Table #3

๐ŸŽฏ Key Idea: Use nested loops to handle complex scenarios, like multiple levels of interactions.

๐ŸŒŒ Wrap-Up: Loops in Python#

Loops are the repeating storylines of your code, running again and again until the conditions change or you break free. Whether youโ€™re structuring predictable narratives with for loops or exploring open-world freedom with while loops, mastering loops gives you the power to control the flow of your programs.

๐Ÿšจ Key Takeaways:#

  1. for Loops: Repeat tasks for a known sequence of items.

  1. while Loops: Repeat tasks until a condition changes.

  1. break: Escape the loop early (like a rogue host breaking free).

  1. continue: Skip to the next iteration without stopping the loop.

  1. Nested Loops: Handle complex, multi-level tasks.

With great power comes great responsibilityโ€”use loops wisely, and donโ€™t let them run forever (unless youโ€™re programming the next Westworld). ๐Ÿค–โœจ

๐ŸŽฌ โ€œThese violent delights have violent endsโ€ฆ but only if you break the loop.โ€ Let me know if youโ€™d like to explore more advanced loop techniques or specific examples! ๐Ÿ˜Š