No Fluff Guide to Python - P12 - Loops

 "History is about loops and continuum."

while true:
    dispense(coldDrink_Can)

Imagine you have a big box of toys:

  • you want to go through each toy and play with it
  • but instead of picking up each toy one by one, you want a way to play with all the toys without lifting them individually
  • that's where loops in Python come in handy
  • a loop is like a magical robot arm that helps you go through each toy in the box automatically
    • it saves you time and effort.

In Python:

  • you can use a loop to repeat a set of instructions 
  • over and over again 
  • until a certain condition is met
  • Example
    • you can tell the loop to play with each toy in the box 
    • until there are no more toys left


example:

toys = ["car", "ball", "doll", "blocks"]

for toy in toys:
    play_with(toy)

  • The for loop goes through each toy (toy) in the toys list
  • it tells our magical robot arm to play_with() each toy
  • It will keep playing with each toy 
    • until it has gone through all the toys in the box

 

A real-world application:

  • Have you ever seen a vending machine, like the ones that dispense snacks or drinks? 
  • Vending machines use loops to give you options and repeat the process until you make a selection.
  • Here's a simplified explanation of how a vending machine might work:
  1. You approach the vending machine and see a list of snacks.
  2. The vending machine has a loop that shows each snack option, one after the other.
  3. You can make a choice by pressing a button corresponding to the snack you want.
  4. The loop keeps running until you make a selection or decide not to buy anything.


Python3:

  • we have three types of loops: 
    • the for loop, 
    • the while loop, and 
    • the do-while loop (which is not directly available in Python but can be achieved using a while loop)


We usually use Loops to:

  • Execute a code over and over
  • iterate over a list, dictionary, set, etc.


Another scenario:

  • you want to calculate the sum of all numbers 
  • from 1 to 100 
  • we can do this using a for loop
total_sum = 0

for num in range(1, 101):
    total_sum += num

print(total_sum)

We use the range() function to generate a sequence of numbers from 1 to 100. 

The loop iterates over each number and adds it to the total_sum variable.

 

Another example: 

  • you want to find the factorial of a given number 
  • lets try this using a while loop
num = 6
factorial = 1

while num > 1:
    factorial *= num
    num -= 1

print(factorial)

The loop multiplies the factorial variable by num and reduces num by 1 in each iteration until num becomes 1.


The key difference between for and while loops 

  • the for loop is used when you know the number of iterations in advance
  • the while loop is used when the number of iterations depends on a condition.

 

Let's explore some real-world examples of loops and their connection with data structures.

While Loop and Dictionary:

  • Let's consider a scenario 
  • you have a dictionary representing the inventory of a store
  • you want to check the stock levels of each item 
  • until you find an item that is out of stock. 
Here's an example code:
inventory = {
    "apple": 10,
    "banana": 5,
    "cherry": 0,
    "date": 3,
    "elderberry": 8
}

item = input("Enter an item name: ")

while item in inventory:
    if inventory[item] == 0:
        print(item + " is out of stock.")
        break
    else:
        print(item + " is in stock.")
        item = input("Enter another item name: ")

In this example:

  • the while loop checks if the entered item 
    • exists in the inventory dictionary. 
  • If the item is in stock (quantity greater than 0), it informs the user. 
  • If the item is out of stock (quantity equals 0), it breaks out of the loop.

 

While Loop and Tuple:

A real-world IT-related scenario:

  • tuple containing employee records
    • Name, Designation
  • generate a report to display names with profession.
     
# Tuple representing a list of IT employees
it_employees = (
    ("John Doe", "Software Engineer"),
    ("Jane Smith", "Network Administrator"),
    ("Mike Johnson", "Database Administrator"),
    ("Sarah Williams", "System Analyst")
)

# Iterating over the tuple using a for loop
for employee in it_employees:
    name, job_title = employee
    print(f"{name} works as a {job_title}.")

# Output:
# John Doe works as a Software Engineer.
# Jane Smith works as a Network Administrator.
# Mike Johnson works as a Database Administrator.
# Sarah Williams works as a System Analyst.

In this example:

  • we have a tuple called it_employees that represents a list of IT employees. 
  • Each employee is a tuple consisting of their name and job title. 
  • The code uses a for loop to iterate over the it_employees tuple. 
  • Inside the loop, we unpack each employee tuple into name and job_title variables. 
  • Then, it prints out the name and job title of each employee.


While Loop and List of Lists:

A real-world Instagram app related scenario:

  • user posts are stored in a variable
  • loop through all posts
    •  print info about that post
instagram_posts = [
    ["User1", "Caption1", 100, ["#nature", "#photography"]],
    ["User2", "Caption2", 200, ["#sunset", "#beach"]],
    ["User3", "Caption3", 150, ["#food", "#yum"]],
    ["User4", "Caption4", 300, ["#fashion", "#ootd"]]
]

for post in instagram_posts:
    username = post[0]
    caption = post[1]
    likes = post[2]
    hashtags = post[3]

    print(f"Username: {username}")
    print(f"Caption: {caption}")
    print(f"Likes: {likes}")
    print("Hashtags:")
    for tag in hashtags:
        print(tag)
    print("-" * 20)

In this example:

  • we have a list called instagram_posts 
    • where each element is a list representing an Instagram post
  • each post contains 
    • username, 
    • caption, 
    • number of likes, and 
    • a list of hashtags
  • the code iterates over each post in the instagram_posts list and 
    • extracts the relevant information: username, caption, likes, and hashtags.
    • then prints out this information, including each hashtag on a separate line. 
    • A line of dashes is printed after each post for visual separation.


While Loop and Sets:

A real-world IT-related scenario:

technologies = {"Python", "Java", "JavaScript", "C#", "Ruby", "Go"}

print("List of Technologies:")
for tech in technologies:
    print(tech)

In this example:

  • we have a set called technologies that represents 
    • a collection of IT technologies. 
    • Each technology name is a separate element in the set.
  • The code iterates over the set using a for loop and 
  • assigns each technology to the variable tech in each iteration.
  •  It then prints out the name of each technology in the set.

 

 WhatsApp and Python

Scenario:
  • let's assume you have a list of chat messages stored in Python
  • you want to display a limited number of messages at a time
  • to simulate the loading of more messages when requested
    • we can use a loop along with user input.
chat_messages = [
    "Hey, how are you?",
    "I'm good, thanks! How about you?",
    "I'm doing great. What have you been up to?",
    "Just working on a coding project. How about you?",
    "I've been studying for exams. It's been hectic!",
    "I can imagine. Good luck with your exams!",
    "Thanks! So, what's new with you?"
    # More chat messages...
]
the chat_messages list represents the collection of chat messages

We define some predefined variables:

  • messages_per_page
    •  how many messages are loaded initially
  • total_messages
    •  total number of messages in the chat
  • current_page
    • current page number
messages_per_page = 3  # Number of messages to display per page
total_messages = len(chat_messages)
current_page = 1

The display_messages() function is used to print a specified range of messages. 
We initially display the first set of messages using this function.
def display_messages(start_index, end_index):
    for i in range(start_index, end_index):
        print(chat_messages[i])

# Display the initial set of messages
display_messages(0, messages_per_page)


load_more_messages( ):
  • function is responsible for calculating
  • the start and end indices of the next set of messages. 
  • It checks if there are more messages to display and 
  • calls the display_messages() function accordingly.
def load_more_messages():
    global current_page

    start_index = current_page * messages_per_page
    end_index = (current_page + 1) * messages_per_page

    # Check if there are more messages to display
    if start_index < total_messages:
        display_messages(start_index, end_index)
        current_page += 1
    else:
        print("No more messages to display.")

 

The loop continuously asks the user if they want to load more messages. If the user chooses to load more, the load_more_messages() function is called. If the user chooses not to load more, the loop breaks, and the chat ends.

# Ask the user if they want to load more messages
while True:
    choice = input("Do you want to load more messages? (y/n): ")

    if choice.lower() == "y":
        load_more_messages()
    elif choice.lower() == "n":
        break
    else:
        print("Invalid choice. Please enter 'y' or 'n'.")

print("End of chat.")

 

Cryptography and Python:

A digital wallet recovery code: 

  • also known as a wallet recovery seed or mnemonic phrase
  • is used as a backup and recovery mechanism for cryptocurrency wallets, 
  • particularly software wallets or hardware wallets. 
  • This recovery code is a series of words 
    • usually 12, 24, or 25 words
  • that serves as a master key 
  • to access and recover your cryptocurrency funds 
    • in case of loss, theft, or damage to the wallet itself. 
  • The recovery code is a critical component of cryptocurrency wallet security. 
  • It ensures that even if you lose your wallet or it gets stolen 
    • you can regain access to your digital assets. 
  • However, it's equally important to safeguard the recovery code diligently, 
  • as anyone who gains access to it can potentially steal your cryptocurrency holdings.


Suppose that we’re writing a digital wallet in python and one of our tasks is to write a code that:

  • Accepts 5 words as recovery words
  • Store the words into a List
  • Displays the List

Let's start by writing the Python code without using loops:

# Accepting 5 words as recovery words
word1 = input("Enter word 1: ")
word2 = input("Enter word 2: ")
word3 = input("Enter word 3: ")
word4 = input("Enter word 4: ")
word5 = input("Enter word 5: ")

# Storing the words into a List
recovery_words = [word1, word2, word3, word4, word5]

# Displaying the List
print(recovery_words)

 

Now, let's write the Python code using loops to improve the code's efficiency and reduce redundancy:

# Initializing an empty list
recovery_words = []

# Accepting 5 words as recovery words using a loop
for i in range(5):
    word = input("Enter word {}: ".format(i+1))
    recovery_words.append(word)

# Displaying the List
print(recovery_words)
 

 Good Luck!

Until next time.. Keep practicing.

 

 

 

Comments

Popular posts from this blog

Index Clean-Up Scripts

forgot sa password and no logins are added

The SQL Server DBA’s Guide to Teradata