Python Basics: Functions
Learn to create reusable code blocks with functions – your coding superpower!
What Are Functions?
A function is like a lunchbox maker – you define it once, and it can create lunches (perform tasks) whenever you need!
Why Use Functions?
- Reuse code: Write once, use many times.
- Organize code: Break complex tasks into smaller steps.
- Simplify debugging: Fix issues in one place.
1. Defining Functions
Use def
to create a function.
Syntax:
def function_name():
# Code to run
Example: A greeting robot!
def greet():
print("Hello! 🌟")
print("How are you?")
# Call the function
greet()
Output:
Hello! 🌟
How are you?
2. Parameters & Arguments: Custom Inputs
Parameter: Variable in the function’s definition.
Argument: Actual value passed to the function.
Example: Pizza Maker
def make_pizza(topping): # Parameter: topping
print(f"🍕 with {topping}")
make_pizza("cheese") # Argument: "cheese"
make_pizza("pineapple") # Argument: "pineapple"
Output:
🍕 with cheese
🍕 with pineapple
Multiple Parameters:
def calc_area(length, width):
area = length * width
print(f"Area: {area} sq units")
calc_area(5, 4) # Output: Area: 20 sq units
3. return: Get Results Back
The return
statement sends a result out of the function.
Example: Math Helper
def add_numbers(a, b):
return a + b
total = add_numbers(3, 7)
print(total) # Output: 10
Key Notes:
return
exits the function immediately.- If no
return
, the function givesNone
.
Advanced Example:
def is_even(num):
return num % 2 == 0
print(is_even(4)) # Output: True
4. Lambda Functions: Quick & Simple
A lambda is a tiny, one-line function without a name.
Syntax:
lambda arguments: expression
Example: Doubler
double = lambda x: x * 2
print(double(5)) # Output: 10
Real-World Use:
# Sort a list of tuples by the second item
points = [(1, 5), (3, 2), (2, 8)]
points.sort(key=lambda point: point[1])
print(points) # Output: [(3, 2), (1, 5), (2, 8)]
Real-World Project: Guessing Game
import random
def generate_number():
return random.randint(1, 10)
def check_guess(secret, guess):
if guess == secret:
return "🎉 Correct!"
elif guess < secret:
return "📉 Too low!"
else:
return "📈 Too high!"
secret_num = generate_number()
guess = int(input("Guess a number (1-10): "))
print(check_guess(secret_num, guess))
Common Mistakes
- ❌ Forgetting
()
when calling a function:greet
vsgreet()
. - ❌ Missing
:
afterdef
orlambda
. - ❌ Using
print()
instead ofreturn
to output a result.
Function Types at a Glance
Type | Syntax | Use Case |
---|---|---|
Regular | def func(): ... | Reusable code blocks. |
Lambda | lambda x: x + 1 | Quick, simple operations. |
Built-in | print(), len(), input() | Predefined by Python. |
Practice Quiz
What’s wrong with this code?
def say_hello
print("Hello")
Answer: Missing ()
after say_hello
.
What does this return?
multiply = lambda a, b: a * b
print(multiply(3, 4))
Answer: 12.
Fun Activity: Mad Libs Generator
def mad_libs(noun, verb):
return f"The {noun} loves to {verb}!"
user_noun = input("Enter a noun: ")
user_verb = input("Enter a verb: ")
print(mad_libs(user_noun, user_verb))
Example Output:
The cat loves to dance!
Key Takeaways
- ✅ Functions are reusable code blocks defined with
def
. - ✅ Parameters are inputs; arguments are actual values.
- ✅ Use
return
to send back results. - ✅ Lambda functions are quick one-liners for simple tasks.
What’s Next?
Learn about file handling to read/write data from files!