- A function in Python is a block of code that performs a specific task or operation and can be called multiple times within a program.
- Functions help break your code into smaller and more manageable parts.
syntax for defining a function in Python:
1 2 3 4 5 |
def function_name(parameters): # Code to be executed # ... return value |
def
is a keyword that is used to define a function.function_name
is the name of the function. It should be a descriptive name that represents what the function does.parameters
are optional and allow you to pass data into the function. You can have multiple parameters separated by commas.- The code to be executed by the function is indented beneath the definition line.
- The
return
keyword is used to return a value from the function.
example of how you could define a function to calculate the average fuel efficiency of a car:
1 2 3 4 5 6 7 8 9 10 |
def average_fuel_efficiency(distance, fuel_consumed): average = distance / fuel_consumed return average # Calling the function and storing the result average = average_fuel_efficiency(100, 5) # Printing the result print(f"Average fuel efficiency: {average} km/l") |
When run, the code outputs:
1 2 |
Average fuel efficiency: 20.0 km/l |