Python Functions — Reusable Code Blocks
Learn how to create your own functions in Python — reusable blocks of code that make your programs organized, shorter, and easier to fix.
What Are Functions?
Your First Function
# Define a function with 'def'
def say_hello():
print("Hello there!")
print("Welcome to Python!")
# Call (use) the function
say_hello() # prints both lines
say_hello() # you can call it as many times as you want!
# Functions with parameters (inputs)
def greet(name):
print(f"Hello, {name}! Nice to meet you!")
greet("Aarav") # Hello, Aarav! Nice to meet you!
greet("Priya") # Hello, Priya! Nice to meet you!Parameters vs Arguments
Functions That Return Values
# Use 'return' to send a result back
def add(a, b):
return a + b
result = add(5, 3)
print(result) # 8
# A more useful example
def calculate_area(length, width):
area = length * width
return area
room = calculate_area(12, 10)
print(f"Room area: {room} sq ft") # Room area: 120 sq ft
# Functions can return any type
def is_passing(score):
return score >= 60 # returns True or False
print(is_passing(85)) # True
print(is_passing(42)) # FalseDefault Values and Multiple Parameters
# Default parameter values
def power(base, exponent=2):
return base ** exponent
print(power(5)) # 25 (uses default exponent 2)
print(power(2, 10)) # 1024 (2 to the power of 10)
# Function with multiple parameters
def introduce(name, age, hobby):
print(f"I'm {name}, {age} years old.")
print(f"I love {hobby}!")
introduce("Meera", 11, "coding")
# Calling with named arguments (order doesn't matter)
introduce(hobby="drawing", name="Zain", age=13)A function should do ONE thing well. If your function is getting really long or doing many different things, break it into smaller functions. For example, instead of one big 'process_order()' function, have 'calculate_total()', 'apply_discount()', and 'print_receipt()'. This makes code way easier to read and fix.
Create these 3 functions: (1) celsius_to_fahrenheit(celsius) that converts Celsius to Fahrenheit using the formula F = C * 9/5 + 32, (2) is_even(number) that returns True if a number is even, False if odd, and (3) longest_word(words) that takes a list of words and returns the longest one. Test each function with at least 2 different inputs!
Ready to build?
Put what you learned into practice — pick a project and start coding.
Start Building Free