10 Monty Python Loops

A

Akubay

New member
Freecoin
170
10 Monty Python Loops
10 different common ways to do loops in Python, with a Monty Python theme + a small quiz
Try to learn from the examples, and your task is a better way to solve Number 0, than 7 lines of print statements
Please comment with your own favorites or just other ways of doing it, so we can all learn new cool ways of using loops

Enjoy 🥳

-----Code below - see pic for indents --
FB_IMG_1673640390973.jpg

#0 Don't do this

print("And now for something completely different...")
print("aNd now for something completely different...")
print("anD now for something completely different...")
print("and now for something completely different...")
print("and Now for something completely different...")
print("and nOw for something completely different...")
print("and noW for something completely different...")

# 1. start with classic for loop over a silly list of Monty Python quotes

quotes = ["It's just a flesh wound.", "Ni!", "I'm not dead yet!"]
for quote in quotes:
print(quote)

# 2. while loops are great for knights that don't know how many times they need to say 'Ni!'. They keep repeating themselves until a certain condition is met

while True:
answer = input("What is the airspeed velocity of an unladen swallow?")
if answer == "African or European?":
break

# 3. range() with for loop is perfect for counting dead parrots. It's a straightforward way of iterating a fixed number of times, for when Mr Death, or the plague, comes knocking ⚰️

for i in range(10):
print("This parrot is no more! He has ceased to be!")

# or
for i in range(10):
print("Bring out your dead! 🛎️")

# 4. For loop with index, using enumerate; perfect for knighting fluffy bunnies like a proper loopy Monarch. Get ready for a schedule of 8 AM Pointy-toothed Knighting Ceremony!

bunnies = ["Thumper", "Benny", "Lola"]
print("Lagomorphic Knighting Schedule:")

for i, bunny in enumerate(bunnies):
print(f"{8+i} AM - Knighting of Sir {bunny}")

# 5. items() method to loop through dictionary can be used to find the Holy Grail. A great way to get key-value pairs and iterate through them

grail_location = {"France": "False", "Coconut": "False", "England": "True"}
for location, has_grail in grail_location.items():
if has_grail == "True":
print(f"The grail is in {location}")
# 6. Recursion is a creative way to loop, like going down the proverbial rabbit hole. Be careful not to get stuck in an infinite rabbit-hole-loop!🐇 ctrl+c/break is your friend 👍

def rabbit_hole(n):
if n > 0:
print("Down the rabbit hole...")
rabbit_hole(n-1)
else:
print("I'm out!")

rabbit_hole(3)

# 7. os.scandir() allows efficient looping through files in a directory. It's a great way to loop through a treasure trove of files, in search of the worlds funniest joke...Just don't read it 👍

import os

for file in os.scandir("quest_files"):
if file.name.endswith(".txt"):
with open(file, "r") as f:
print(f.read())

# 8. enumerate() function gives access to both index and value when looping through terable Perhaps keep track of brave knights, Robin not really the ’leading from the front’-type, however. Completely different to previous enumerate example, or maybe I like enumerate alot😉

knights = ["Lancelot", "Galahad", "Robin"]
for index, knight in enumerate(knights):
print(f"{index+1}. {knight}")

# 9. zip() is great for looping through multiple iterables in parallel, like holy hand grenades and their counts. Is it throw on 3, or... 🤔

counts = [3,2,1]
grenades = ["Holy Hand Grenade of Antioch", "Holy Hand Grenade of Jerusalem", "Dynamite"]

for count, grenade in zip(counts, grenades):
print(f"{count} {grenade}")

# 10. itertools for unusual looping, like creating infinite sequences of 'Ni!'. A great way to loop indefinitely, if you hate trees...or shrubberies

import itertools
for ni in itertools.cycle(["Ni!"]):
print(ni)
 

Richest Freecoded User

Most Freecoin

freecoded
freecoded
2,182 Freecoin
Davy200
Davy200
590 Freecoin
nathan69
nathan69
424 Freecoin
Laureine
Laureine
415 Freecoin
C
codeguru
295 Freecoin
Tekera
Tekera
263 Freecoin
A
Akubay
170 Freecoin
smitha
smitha
104 Freecoin
G
Gabby
93 Freecoin
S
sesli
78 Freecoin
Top