0
0
Pythonprogramming~20 mins

List comprehension vs loop in Python - Hands-On Comparison

Choose your learning style9 modes available
List comprehension vs loop
๐Ÿ“– Scenario: You work in a small bakery. Every day, you record the number of cookies sold in a list. You want to find out how many cookies you sold each day after giving a 10% discount on the price per cookie.
๐ŸŽฏ Goal: Build a program that calculates the discounted cookie prices using both a for loop and a list comprehension. Compare the results.
๐Ÿ“‹ What You'll Learn
Create a list called cookie_prices with exact values: 2.0, 2.5, 3.0, 2.75, 3.25
Create a variable called discount_rate and set it to 0.10
Use a for loop with variable price to create a list called discounted_prices_loop with prices after discount
Use a list comprehension with variable price to create a list called discounted_prices_comp with prices after discount
Print both discounted_prices_loop and discounted_prices_comp
๐Ÿ’ก Why This Matters
๐ŸŒ Real World
Calculating discounts on product prices is common in stores and online shops to attract customers.
๐Ÿ’ผ Career
Understanding loops and list comprehensions helps in data processing tasks, which are common in programming jobs.
Progress0 / 4 steps
1
Create the list of cookie prices
Create a list called cookie_prices with these exact values: 2.0, 2.5, 3.0, 2.75, 3.25
Python
Need a hint?

Use square brackets [] to create a list with the given numbers separated by commas.

2
Set the discount rate
Create a variable called discount_rate and set it to 0.10
Python
Need a hint?

Use the equals sign = to assign the value 0.10 to the variable discount_rate.

3
Calculate discounted prices using a for loop and a list comprehension
Use a for loop with variable price to create a list called discounted_prices_loop with prices after discount. Then use a list comprehension with variable price to create a list called discounted_prices_comp with prices after discount.
Python
Need a hint?

In the for loop, multiply each price by (1 - discount_rate) and add it to discounted_prices_loop. In the list comprehension, do the same calculation inside square brackets.

4
Print the discounted prices lists
Print the list discounted_prices_loop and then print the list discounted_prices_comp
Python
Need a hint?

Use two print statements, one for each list.