💻 3.
Computer Science 110: Intro to Programming
Date: Nov 4, 2025
Professor: Prof. T. Huang
Topic: Functions and Variable Scope in Python
Concept Overview:
Functions are reusable blocks of code designed to perform a specific task. They
improve modularity, readability, and debugging efficiency.
Function Basics:
Defined with def keyword.
May include parameters (inputs) and a return value (output).
Can be called multiple times throughout a program.
Example:
def greet(name):
print("Hello,", name)
greet("Alice")
Output: Hello, Alice
Variable Scope:
Local variables: exist only inside the function.
Global variables: exist throughout the program.
Scope hierarchy (LEGB): Local → Enclosing → Global → Built-in.
Example of Scope Issue:
x = 10
def change():
x = 5
print(x) # local
change()
print(x) # global
Output:
5
10
Advanced Topics:
Default arguments and keyword arguments.
Recursion (functions calling themselves).
Lambda functions for short, throwaway logic.
Professor’s Tip:
“If you find yourself copying code more than twice—write a function instead.”
Homework:
Write a recursive function that returns the Fibonacci sequence up to n.
Bonus: Add type hints and docstrings.