Functions are one of the most powerful concepts in programming:
What functions are and why to use them
Defining and calling functions
Parameters and arguments
Return values
Default parameters
âī¸ What is a Function?
A function is a reusable block of code that does a specific task. Instead of writing the same code over and over, you can put it in a function and call it when needed.
đĄ Analogy: Think of a function like a recipe. You write the recipe once (define the function), and then you can follow it anytime you need it (call the function).
Why Use Functions?
Don't repeat yourself (DRY) - Write once, use many times
Organization - Break code into logical chunks
Easy to test - Test each function separately
Reusability - Use functions in other programs
đ Defining a Function
Use the def keyword to create a function:
Basic Syntax:
deffunction_name():
# Code inside the functionprint("Hello!")
Calling a Function:
defgreet():
print("Hello!")
# Call the functiongreet()
greet()
greet()
Hello!
Hello!
Hello!
đĨ Parameters and Arguments
Functions can accept input values called parameters:
Function with Parameter:
defgreet(name):
print("Hello, " + name + "!")
greet("Alex")
greet("Jordan")
greet("Taylor")
â ī¸ Important: Parameters with default values must come AFTER parameters without defaults.
đ Scope
Variables inside a function are local - they don't affect variables outside:
defdouble(x):
x = x * 2print("Inside function:", x)
number = 5double(number)
print("Outside function:", number)
Inside function: 10
Outside function: 5
đī¸ Exercise: Calculator Function
Create a calculator function that performs basic operations:
# Create a function called calculate# It should take three parameters: num1, operation, num2# operation can be: "+", "-", "*", "/"# Return the result# Example:# calculate(10, "+", 5) should return 15# calculate(10, "*", 5) should return 50
Bonus Challenge:
Handle division by zero and return "Cannot divide by zero!"