Defining Functions
Defining your own functions in Python allows you to create reusable blocks of code tailored to specific tasks.
In Python, a function is a block of organized, reusable code that performs a single, related action. Functions help break down complex problems into smaller, manageable parts, making your code more modular and easier to understand.
Why Use Functions?
Reusability: Write once, use multiple times. Functions allow you to reuse code without rewriting it.
Modularity: Break down complex tasks into simpler, more manageable pieces.
Readability: Functions make your code cleaner and easier to read.
To define a function in Python, use the def
keyword, followed by the function name and parentheses ()
. Inside the parentheses, you can specify parameters that the function will accept. The function body is indented and contains the code to be executed. In this example, greet_artist
is a function that takes one parameter, artist_name
, and prints a greeting message. To execute a function, you need to call it by its name and provide any required arguments.
def greet_artist(artist_name): print(f"Hello, {artist_name}! Welcome to the stage.") greet_artist("Freddie Mercury")
Imagine you want to calculate the average duration of tracks in an album. You can define a function to perform this calculation.
def calculate_average_duration(durations_list): total_duration = sum(durations_list) number_of_tracks = len(durations_list) average_duration = total_duration / number_of_tracks return average_duration # Usage track_durations = [354, 183, 482, 431] average = calculate_average_duration(track_durations) print(f"Average track duration: {average} seconds")
Swipe to start coding
Your goal is to create the is_radio_friendly
function that determines if a track is radio friendly based on its duration. A track is considered radio friendly if its duration is between 3 and 4 minutes, inclusive. This function is useful for organizing and categorizing tracks based on their suitability for radio play.
Inputs:
duration_ms
: An integer representing the duration of the track in milliseconds.
Steps:
-
Check Duration: Use comparison operators to determine if
duration_ms
is between 180,000 and 240,000 milliseconds (inclusive). -
Return the Result: Ensure the function returns a boolean indicating whether the track is radio friendly.
Lösung
Danke für Ihr Feedback!