CBSERanker

Loading

Python Functions Class Notes

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() or range(), 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

  1. Required Arguments:
    • Must pass all parameters in order.
    pythonCopydef person_info(name, age): print(f”{name} is {age} years old.”) person_info(“Bob”, 30) # Works person_info(“Bob”) # Error → Missing ‘age’
  2. Keyword Arguments:
    • Specify arguments by parameter name (order doesn’t matter).
    pythonCopyperson_info(age=25, name=”Alice”) # Works → Output: “Alice is 25 years old.”
  3. Default Arguments:
    • Set a default value if no argument is passed.
    pythonCopydef order_food(item, quantity=1): # Default quantity = 1 print(f”{quantity} x {item}”) order_food(“pizza”) # Output: “1 x pizza” order_food(“burger”, 3) # Output: “3 x burger”
  4. Variable-Length Arguments (*args):
    • Accept any number of arguments. Works like a tuple.
    pythonCopydef sum_all(*numbers): total = 0 for num in numbers: total += num return total print(sum_all(2, 5, 10)) # Output: 17

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.

Leave a Reply

Your email address will not be published. Required fields are marked *