Neural Sync Active
Week 4: Functions, Variable Scope, and Dictionaries
Registry Synced
Week 4: Functions, Variable Scope, and Dictionaries
472 words
2 min read
Course: Jan 2026 - Python Difficulty: Advanced Setup Focus: Code reusability, function parameters, mapping key-values.
1. Functions
A function is a reusable block of code designed to perform a specific task. Functions make code modular, easier to read, and eliminate repetition.
1.1 Defining and Calling
Use the
def keyword to create a function.python# Definition def greet(name): print(f"Hello, {name}!") # Calling functions greet("Alice") greet("Bob")
1.2 Arguments and Return Values
Functions can take inputs (parameters/arguments) and send data back (return values).
pythondef add_numbers(a, b): result = a + b return result sum_val = add_numbers(5, 7) print(sum_val) # Output: 12
Note: A function terminates immediately upon hitting a
return statement.1.3 Default Arguments
You can provide default values for parameters, making them optional during the call.
pythondef power(base, exponent=2): return base ** exponent print(power(3)) # Output: 9 (defaults to squaring) print(power(3, 3)) # Output: 27
2. Variable Scope
Scope defines where in your code a variable can be accessed.
- Local Scope: Variables created inside a function. They only exist while the function is running.
- Global Scope: Variables created outside all functions. They are accessible anywhere in the file.
pythonx = 10 # Global def my_func(): y = 5 # Local print(x) # Accessing global. Prints 10 my_func() # print(y) <-- ERROR: 'y' is not defined in the global scope
To modify a global variable inside a function, you must use the
global keyword.3. Dictionaries
A Dictionary is an unordered, mutable collection of key-value pairs. It allows for fast retrieval of data based on a unique key. They are defined using curly braces
{}.3.1 Creating and Accessing
Keys must be immutable types (strings, numbers, tuples). Values can be anything.
pythonstudent = { "name": "John", "age": 20, "courses": ["Math", "Physics"] } print(student["name"]) # Output: 'John'
3.2 Modifying and Adding Elements
python# Modifying student["age"] = 21 # Adding a new key-value pair student["grade"] = "A"
3.3 Dictionary Methods
keys(): Returns a list-like object of all keys.values(): Returns all values.items(): Returns tuples of(key, value).get(key, default): Safely gets a value. If the key doesn't exist, it returns thedefaultvalue instead of crashing.
3.4 Iterating Over Dictionaries
python# Iterating over keys for key in student: print(key, "->", student[key]) # Iterating over items for k, v in student.items(): print(f"{k}: {v}")
Use
.get() when you aren't absolutely sure a key exists. student["address"] crashes if address is missing, whereas student.get("address", "Unknown") gracefully returns "Unknown".🧭 Navigation
- 📘 Textbook Notes: Week 4 Notes
- 📝 Assignment: Week 4 Assignment
- ⬅️ Previous Week: Week 3 Notes