Lesson 4

Interstellar Strolls Through Python: Loop and Conditional Symbiosis

Lesson Introduction: Combining Loops with Conditionals - The Power Duo

Greetings, student! Today, we're fusing Python loops and conditionals together. Conditionals empower our code to make decisions, while loops enable the execution of repetitive tasks. Let's master this synergy!

The Basics of Conditions in Loops

Loops, such as for and while, repeat specific tasks, and conditionals — if, elif, and else — guide the path of the code. Combining these constructs equips us with a virtual super robot that performs repeated tasks with decision-making abilities.

Let's consider sending personalized party invitations. In this context, loops go through each guest, and conditionals decide the style of the invitation:

Python
1# Invite guests using a loop with a conditional 2# Each guest has a name and invitation type - VIP or Regular 3guests = [('Alice', 'VIP'), ('Bob', 'VIP'), ('Tom', 'Regular'), ('Jerry', 'Regular')] 4 5for guest in guests: 6 if guest[1] == 'VIP': 7 print("Dear", guest[0], ", join us for a grand celebration!") 8 elif guest[1] == 'Regular': 9 print("Hi", guest[0], ", you are invited!")

This code prints:

Markdown
1Dear Alice , join us for a grand celebration! 2Dear Bob , join us for a grand celebration! 3Hi Tom , you are invited! 4Hi Jerry , you are invited!
Working with Conditionals in For Loops

Python’s For Loop iterates over a defined sequence of elements. When we pair a conditional with the loop, the execution adjusts with each iteration based on the condition.

For instance, consider hosting a party. We have a guest_list and an unwanted_list. By pairing a For Loop with a conditional, we can ensure that only welcomed guests gain admission:

Python
1# For Loop with a conditional 2guest_list = ['Alice', 'Bob', 'Tom', 'Jerry', 'Snow'] 3unwanted_guests = ['Tom', 'Snow'] 4 5for guest in guest_list: 6 if guest not in unwanted_guests: 7 print("Welcome,", guest, "!") 8 else: 9 print("Sorry,", guest, ", the party is full.")

The code prints:

Markdown
1Welcome, Alice ! 2Welcome, Bob ! 3Sorry, Tom , the party is full. 4Welcome, Jerry ! 5Sorry, Snow , the party is full.
Implementing Conditionals in While Loops

A While Loop continues as long as its condition remains valid. Inserting a conditional within it can alter or halt its iterations based on changing conditions.

Suppose that when an unwanted guest arrives, the doorman closes the gate:

Python
1# While Loop with a conditional 2guest_list = ['Alice', 'Bob', 'Tom', 'Jerry', 'Snow'] 3unwanted_guests = ['Tom', 'Snow'] 4guest_index = 0 5 6while guest_index < len(guest_list): 7 if guest_list[guest_index] not in unwanted_guests: 8 print("Please come in,", guest_list[guest_index], "!") 9 else: 10 print("Party Over:", guest_list[guest_index], "showed up!") 11 break # This will stop the while loop completely 12 guest_index += 1

The code prints:

Markdown
1Please come in, Alice ! 2Please come in, Bob ! 3Party Over: Tom showed up!
Understanding Different Scenarios

The combination of loops and conditionals provides immense versatility. For instance, consider these scenarios:

  1. Picking out even numbers from a list.
  2. Find all duplicates in the list of numbers.

Here's how we can address these scenarios:

Python
1# Filter out even numbers 2numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9] 3for num in numbers: 4 if num % 2 != 0: # if the number is not divisible by 2 5 print(num) 6""" 7Prints: 81 93 105 117 129 13""" 14 15# Find all duplicates in the list of numbers 16num_list = [1, 3, 5, 3, 7, 2, 1] 17unique_list = [] 18for num in num_list: 19 if num not in unique_list: 20 unique_list.append(num) 21 else: 22 print("Duplicate number found:", num) 23""" 24Prints: 25Duplicate number found: 3 26Duplicate number found: 1 27"""
Lesson Summary: The Power Duo in Action

Fantastic! You've learned to combine Python's loops and conditionals. We've covered for and while loops coupled with conditionals and showcased Python examples, using our combination to solve various scenarios.

Now, it's time to exercise this new skill through practice. Just as a dancer perfects a dance routine by repeating each step, mastering these concepts requires ample practice. Let's continue our journey to Python mastery!

Enjoy this lesson? Now it's time to practice with Cosmo!

Practice is how you turn knowledge into actual skills.