Statement of Completion#aea40f8d
Control Flow
medium
Control Flow Mastery
Resolution
Activities
Project.ipynb
1. Which of the following statements about match-case in Python is true?¶
In [ ]:
2. Identify the Operator Used for Short-Circuit Evaluation in AND Condition¶
In [ ]:
3. What happens if no except block matches the exception?¶
In [ ]:
4. What does raise ... from syntax in Python Help with?¶
In [ ]:
5. Determine the output of bool([]) in Python.¶
In [ ]:
6. Identify the context manager from the options¶
In [ ]:
7. Identify the keyword used to define a generator function¶
In [ ]:
8. What does the following code print?¶
In [ ]:
9. Determine the output of the following code.¶
In [ ]:
10. Determine what the following code prints¶
In [ ]:
11. Determine the result of the following code.¶
In [1]:
[i for i in range(5) if 1 > 10]
Out[1]:
[]
12. Determine the result of the following list comprehension.¶
In [ ]:
13. Predict the output of the following code¶
In [3]:
lst = [1, 1, 2]
all(lst)
Out[3]:
True
14. Determine the output of the following code.¶
In [10]:
def gen():
yield 1
yield 2
In [13]:
g = gen()
print(next(g))
1
15. What is the result of the following code?¶
In [ ]:
16. Determine the output of the following code.¶
In [15]:
def greet():
try:
return "Hi"
finally:
return "Bye"
print(greet())
Bye
17. Count the Odd Numbers¶
In [21]:
def count_odds(lst):
return len([i for i in lst if i % 2 != 0])
count_odds([1, 2, 3, 4, 5, 6])
Out[21]:
3
18. Determine if it is Pizza Day¶
In [26]:
def is_pizza_day(day):
return "Order Pizza!" if day == "Friday" or day == "Saturday" else "Eat Healthy!"
is_pizza_day("Friday")
Out[26]:
'Order Pizza!'
19. Check Lucky Multiples¶
In [28]:
def check_lucky_numbers(lst):
multi = [True if num % 7 == 0 or num % 9 == 0 else False for num in lst]
return "All numbers are lucky!" if all(multi) else "Unlucky number found!"
In [30]:
check_lucky_numbers([7, 9])
Out[30]:
'All numbers are lucky!'
In [ ]:
def check_lucky_numbers(lst):
for num in lst:
if num % 7 != 0 and num % 9 != 0:
return "Unlucky number found!"
return "All numbers are lucky!"
20. Decide Whether to Watch a Movie¶
In [35]:
def should_watch(rating, genre):
return "Watch" if rating > 7 and genre != "Horror" else "Skip"
In [37]:
should_watch(8, "Action")
Out[37]:
'Watch'
21. Count Words That Start with Capital Letters¶
In [39]:
def count_caps(words):
return len([word for word in words if word[0].isupper()])
count_caps(["aaa", "Bfff", "ccc", "Deed"])
Out[39]:
2
22. Define a Function to Detect Traffic Light Action¶
In [43]:
def traffic_action(color):
match color:
case "Red":
return "Stop"
case "Yellow":
return "Slow down"
case "Green":
return "Go"
case _:
return "Invalid signal"
23. Calculate the Average of a given List¶
In [50]:
def safe_average(values):
num_vals = []
for value in values:
try:
num_vals.append(float(value))
except (ValueError, TypeError):
continue
if num_vals:
return sum(num_vals) / len(num_vals)
else:
return "No numeric data found"
In [51]:
safe_average(["2", 5, "aa", "bbb", "5"])
Out[51]:
4.0
24. Process the Order with Custom Error¶
In [70]:
class OutOfStockError(Exception):
pass
def process_order(stock, order_qty):
try:
if order_qty > stock:
raise OutOfStockError(f"Only {stock} items left")
return "Order Confirmed"
except OutOfStockError as e:
return str(e)
In [71]:
process_order(8, 10)
Out[71]:
'Only 8 items left'
25. Read the First Line Safely¶
In [77]:
def read_first_line(filename):
try:
with open(filename, "r") as f:
return f.readline().strip()
except FileNotFoundError:
return "File not found"
26. Implement a Smart Step Counter¶
In [117]:
class StepCounter:
def __init__(self, daily_steps):
self.daily_steps = daily_steps
def generate_rewards(self, threshold):
reward_given = False
for i, step in enumerate(self.daily_steps, start=1):
if step > threshold:
reward_given = True
yield f"Day {i}: Reward unlocked for {step} steps!"
if not reward_given:
yield "No rewards"
def collect_rewards(generator_obj):
return list(generator_obj)
In [119]:
class StepCounter:
def __init__(self, steps):
self.steps = steps
def generate_rewards(self, threshold):
rewarded = False
for i, step in enumerate(self.steps, 1):
if step > threshold:
rewarded = True
yield f"Day {i}: Reward unlocked for {step} steps!"
if not rewarded:
yield "No rewards"
def collect_rewards(generator_obj):
return list(generator_obj)
In [115]:
steps = [5000, 12000, 8000, 15000, 7000]
tracker = StepCounter(steps)
reward_gen = tracker.generate_rewards(threshold=10000)
messages = collect_rewards(reward_gen)
print(messages)
['Day 2: Reward unlocked for 12000 steps!', 'Day 4: Reward unlocked for 15000 steps!']
In [ ]: