While Loops
Today, we'll explore the while loop in Python, a powerful tool that allows you to repeat actions until a certain condition is met. This concept is essential in data analytics, where you often need to process data iteratively.
In Python, a while loop continues to execute a block of code as long as a specified condition is true. Think of it like a musician practicing a section of a song repeatedly until they master it. The loop will keep running until the condition becomes false.
Basic Structure:
python
Example:
Imagine you're tracking the practice time of a musician. You want to keep practicing until a certain number of hours is reached:
practice_hours = 0 goal_hours = 5 while practice_hours < goal_hours: print("Keep practicing!") practice_hours += 1 print("Practice goal reached!")
In this example, the loop will print "Keep practicing!" and increment practice_hours
by 1 until it reaches goal_hours
. Once the condition practice_hours < goal_hours
is no longer true, the loop stops, and "Practice goal reached!" is printed.
Let's say you have a list of song durations and you want to calculate the total duration until a certain limit is reached:
song_durations = [3, 4, 5, 2, 6] # in minutes total_duration = 0 limit = 10 index = 0 while index < len(song_durations) and total_duration + song_durations[index] <= limit: total_duration += song_durations[index] index += 1 print("Total Duration:", total_duration, "minutes")
In this example, the loop iterates through the song_durations
list, adding each duration to total_duration
until the limit is reached.
Swipe to start coding
Complete the count_popular_tracks
function that counts the number of tracks with a popularity score greater than a specified threshold. This function will utilize a while loop to iterate over the tracks dataset.
Inputs:
tracks
: A list of dictionaries, where each dictionary represents a track and contains a key'track_popularity'
with an integer value.threshold
: An integer representing the popularity score threshold.
Steps:
-
Iterate Over Tracks:
- Use a while loop to iterate over the
tracks
list until the end of the list is reached. - Inside the loop, check if the popularity score of the current track (accessed via
tracks[index]['track_popularity']
) is greater than thethreshold
.
- Use a while loop to iterate over the
-
Update Count: If the condition is met, increment the
count
by 1. -
Increment Index: Increment the
index
by 1 to move to the next track.
Løsning
Takk for tilbakemeldingene dine!