Module 5 notes ?
Module 5 notes ?
Example Variables:
name = "Meiying"
lab1_grade = 78
lab2_grade = 90
midterm = 89
final = 30
Desired Output:
1.Concatenation (+)
Simple
Messy for long strings
3️. str.format()
output = "Student name: {}\nLab grade:\n\tlab1_grade: {}...".format(name,
lab1_grade, ...)
4️. f-Strings
Execution Order:
Python evaluates arguments from left to right before passing them to the outer function.
3. Preconditions
Example Function:
def average_rating(rating_1: int, rating_2: int, rating_3: int) -> float:
"""Return the average rating given the ratings are 1 to 5."""
Preconditions:
Typical Cases:
is_palindrome("noon") → True
is_palindrome("hello") → False
Edge Cases:
Empty string: is_palindrome("") → True
Single character: is_palindrome("c") → True
Different Scenarios:
Short strings: "aba" (True), "ac" (False)
Long strings: "redder" (True), "banana" (False)
Non-words: "cda9adc" (True), "akgwefd04" (False)
Case sensitivity: "Civic" (False unless lowercased in function)
Contract Violations:
is_palindrome(35) → Error!
Why test these? To ensure the function handles all possible inputs correctly.
1️. Local Scope First: Python looks inside the function first. If not found, it checks the global
scope.
2️. Modifying Globals: Use global to modify global variables inside functions (avoid this—it’s
error-prone!).
Best Practice: Pass globals as arguments instead of modifying them inside functions.
6. Memory Model
How Python Stores Data:
Example:
def foo():
x = 1 # Local variable
foo()
print(x) # Error! 'x' is local to foo().
Memory Visualization:
[main frame]
- Variables: None
[foo frame]
- x: 1
def foo_2(c):
c *= 2
return c
a = 3
a = foo_1(a) # Result: a = 3 + (3*2) = 9
Step-by-Step Execution:
1️.foo_1(3) is called.
2️.Inside foo_1, foo_2(3) is called → returns 6.
3️.b becomes 3 + 6 = 9.
4️.a is updated to 9.
def foo():
foo() # Calls itself infinitely!
Why? Each recursive call adds a new frame to the stack. Without a base case, the stack fills
up!
PI = 3.14159
def degree_to_radian(deg):
return deg * PI / 180
Use named constants instead of unexplained numbers.
Summary
Scope Rules: Local → Global. Use global rarely.
Test Thoroughly: Cover edge cases, contracts, and typical use.
Memory Frames: Each function call creates a new frame.
Clean Code: Avoid globals, use f-strings, and name your constants