What are Functions in Python? Explained in 3 Minutes (Common Questions #2)
Video: What are Functions in Python? Explained in 3 Minutes (Common Questions #2) by Taught by Celeste AI - AI Coding Coach
Watch full page →What are Functions in Python? Explained in 3 Minutes
Functions in Python are reusable blocks of code designed to perform a specific task. This guide covers built-in functions like print() and len(), how to define your own functions using def, and the importance of return values and parameters to make your code modular and efficient.
Code
# Using built-in functions
print("Hello, world!") # Prints text to the console
length = len([1, 2, 3, 4]) # Returns the length of the list
print("Length:", length)
# Defining your own function
def greet(name):
"""Returns a greeting message for the given name."""
return "Hello, " + name + "!"
# Calling the function with a parameter
message = greet("Alice")
print(message)
# Function with multiple parameters and a calculation
def add_numbers(a, b):
return a + b
result = add_numbers(5, 7)
print("Sum:", result)
# Practical helper function example
def is_even(number):
"""Returns True if the number is even, False otherwise."""
return number % 2 == 0
print("Is 10 even?", is_even(10))
print("Is 7 even?", is_even(7))
Key Points
- Functions encapsulate reusable code blocks to keep programs organized and avoid repetition.
- Built-in functions like
print()andlen()provide common utilities without extra code. - Use
defto define your own functions with parameters and optional return values. - Return values allow functions to output results that can be stored or used later.
- Functions support the DRY (Don't Repeat Yourself) principle, making code easier to maintain and debug.