Python Functions Class Notes
What’s a Function?
- A function is a block of code you define once and reuse as much as you want.
- Think of it like a mini-program inside your bigger program. Instead of rewriting the same code over and over, you just call the function.
- Python has built-in functions like
print()
orrange()
, but you can also make your own (user-defined functions).
Why Use Functions?
- Avoid repetition: Write once, use everywhere.
- Stay organized: Split big programs into smaller, manageable pieces.
- Easy fixes: Change one function, and it updates everywhere it’s used.
- Save time: Reusability is king!
How to Create a Function
Use the def
keyword to define a function. Indentation matters!
python
Copy
def greet(): # Define print("Hello!") # Code inside (indented) greet() # Call the function → Prints "Hello!"
Parameters & Arguments
- Parameters are inputs your function accepts.
- Arguments are the actual values you pass in.
Example:
python
Copy
def say_hi(name): # 'name' is a parameter print(f"Hi, {name}!") say_hi("Alice") # "Alice" is the argument → Output: "Hi, Alice!"
Returning Values
Use return
to send data back from a function.
python
Copy
def add(a, b): return a + b result = add(3, 5) # result = 8
How Python Handles Variables in Functions
- Mutable objects (like lists): Changes inside the function affect the original.
- Immutable objects (like strings): Changes inside the function don’t affect the original.
Example with a list:
python
Copy
def add_items(shopping_list): shopping_list.append("milk") my_list = ["eggs"] add_items(my_list) print(my_list) # Output: ["eggs", "milk"] → Original list changed!
Example with a string:
python
Copy
def update_greeting(text): text = text + "!!!" # Creates a new string greeting = "Hello" update_greeting(greeting) print(greeting) # Output: "Hello" → Original stays the same!
Types of Arguments
- Required Arguments:
- Must pass all parameters in order.
- Keyword Arguments:
- Specify arguments by parameter name (order doesn’t matter).
- Default Arguments:
- Set a default value if no argument is passed.
- Variable-Length Arguments (
*args
):- Accept any number of arguments. Works like a tuple.
Scope of Variables
- Local variables: Inside a function. Can’t be used outside.
- Global variables: Outside all functions. Accessible everywhere.
Example:
python
Copy
global_var = "I’m global!" def test_scope(): local_var = "I’m local!" print(global_var) # Works test_scope() print(local_var) # Error → local_var doesn’t exist here!
Key Takeaways
- Functions = reusable code blocks. Use
def
to create them. - Parameters are placeholders; arguments are actual values.
- Return results with
return
. - Mutable vs immutable affects if changes stick outside the function.
- Arguments can be required, keyword, default, or variable-length.
- Scope rules: Local stays inside, global works everywhere.