CMPSC 100 Computational Expression
Breaking code into reusable pieces
Functions are reusable blocks of code that perform specific tasks - think of them as “mini-programs” that help organize code and avoid repetition.
You’ve already been using functions in every lab:
Every time you use parentheses (), you are calling a function!
Key parts: def keyword, function name, parameters in (), colon :, indented body, optional return
Key Terms:
name - the variable in the function definition"Maya" - the actual value passed when calling the functionOutput:
Meet Zara!
Major: Computer Science
Year: Sophomore
Meet Kai!
Major: Mathematics
Year: Junior
Functions can return values back to the caller:
Return vs. Print:
return sends a value back for use elsewhereprint() displays output but returns Nonedef calculate_area(length, width):
"""Calculates the area of a rectangle"""
return length * width
def grade_to_letter(score):
"""Converts numeric grade to letter grade"""
if score >= 90:
return "A"
elif score >= 80:
return "B"
elif score >= 70:
return "C"
elif score >= 60:
return "D"
else:
return "F"
# Using the functions
area = calculate_area(5, 3)
grade = grade_to_letter(85)
print(f"Area: {area}, Grade: {grade}") # Area: 15, Grade: BPython provides useful built-in functions for finding minimum and maximum values:
# Finding min and max of numbers
scores = [78, 92, 85, 69, 94, 88]
highest_score = max(scores)
lowest_score = min(scores)
print(f"Highest: {highest_score}, Lowest: {lowest_score}") # Highest: 94, Lowest: 69
# Constraining values within bounds (useful for user input validation)
def get_valid_rounds():
"""Gets number of rounds from user, constrained between 3 and 6"""
rounds = int(input("How many rounds (3-6)? "))
rounds = max(3, min(6, rounds)) # Ensures rounds is between 3 and 6
return rounds
# Finding extremes among multiple values
temperature_readings = [72.5, 68.2, 75.1, 70.8, 73.3]
temp_range = max(temperature_readings) - min(temperature_readings)
print(f"Temperature range: {temp_range}°F") # Temperature range: 6.9°Fdef count_down(start):
"""Counts down from start to 1"""
for i in range(start, 0, -1):
print(i)
print("Blast off!")
def sum_list(numbers):
"""Calculates sum of numbers in a list"""
total = 0
for num in numbers:
total = total + num
return total
# Using the functions
count_down(3) # Prints: 3, 2, 1, Blast off!
my_numbers = [1, 2, 3, 4, 5]
result = sum_list(my_numbers)
print(f"Sum: {result}") # Sum: 15import random
def roll_dice():
"""Simulates rolling a six-sided die"""
return random.randint(1, 6)
def create_random_sequence(length):
"""Creates a random sequence of numbers"""
sequence = []
for i in range(length):
number = random.randint(0, 2) # Random number 0, 1, or 2
sequence.append(number)
return sequence
# Using random functions
dice_roll = roll_dice()
random_seq = create_random_sequence(5)
print(f"Dice: {dice_roll}") # Dice: 4 (random)
print(f"Sequence: {random_seq}") # Sequence: [1, 0, 2, 1, 0] (random)Output:
Hello, Student Amara!
Hello, Professor Dr. Patel!
Local vs Global Variables:
def my_function():
local_var = "I'm local!" # LOCAL: Only exists inside function
print(local_var)
global_var = "I'm global!" # GLOBAL: Available everywhere
def another_function():
print(global_var) # Can access global variables
# print(local_var) # Error! Can't access other function's local variables
my_function() # Prints: I'm local!
another_function() # Prints: I'm global!Key Rules:
Before using hardware functions, we need to import them:
Two ways to import:
import module_name - imports the whole modulefrom module_name import function_name - imports specific functions# Validation functions
def is_valid_email(email):
return "@" in email
def is_positive(number):
return number > 0
# Conversion functions
def inches_to_centimeters(inches):
return inches * 2.54
# Processing functions
def get_initials(first_name, last_name):
return first_name[0].upper() + last_name[0].upper()
def count_vowels(text):
vowels = "aeiouAEIOU"
count = 0
for char in text:
if char in vowels:
count += 1
return countAlways test your functions with different inputs:
Create a function when you:
Functions help you:
In our labs, we organize code using a main function:
Why use this pattern?
__name__The magic line: if __name__ == "__main__":
Python automatically sets __name__:
__name__ = "__main__"__name__ = "filename"This prevents your main program from running when someone imports your file!