0% found this document useful (0 votes)
8 views

Module 5 notes ?

Module 5 covers string formatting methods in Python, including concatenation, old-style formatting, str.format(), and f-strings, with f-strings being the most recommended. It discusses the importance of preconditions, test cases for functions like is_palindrome, and the distinction between global and local variables. Additionally, it highlights memory management in Python, coding style tips, and the significance of avoiding global variables and using named constants.

Uploaded by

bamese3331
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views

Module 5 notes ?

Module 5 covers string formatting methods in Python, including concatenation, old-style formatting, str.format(), and f-strings, with f-strings being the most recommended. It discusses the importance of preconditions, test cases for functions like is_palindrome, and the distinction between global and local variables. Additionally, it highlights memory management in Python, coding style tips, and the significance of avoiding global variables and using named constants.

Uploaded by

bamese3331
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 6

Module 5 notes

1. Formatting Strings (Q1)


Task: Format a string using all four methods (given variables name, lab1_grade, etc.).

Example Variables:
name = "Meiying"
lab1_grade = 78
lab2_grade = 90
midterm = 89
final = 30

Desired Output:

Student name: Meiying


Lab grade:
lab1_grade: 78
lab2_grade: 90
- midterm: 89
- final: 30

4 Ways to Format Strings

1.Concatenation (+)

output = "Student name: " + name + "\nLab grade:\n\tlab1_grade: " +


str(lab1_grade) + ...

Simple
Messy for long strings

2️. Formatting (Old Style)

output = "Student name: %s\nLab grade:\n\tlab1_grade: %d..." % (name,


lab1_grade, ...)

Use %s for strings, %d for integers

3️. str.format()
output = "Student name: {}\nLab grade:\n\tlab1_grade: {}...".format(name,
lab1_grade, ...)

Supports positional ({0}) or named ({name}) arguments

4️. f-Strings

output = f"Student name: {name}\nLab grade:\n\tlab1_grade: {lab1_grade}..."

Best choice! Clean and readable.

2. Nested Function Calls


Example:
def area(length, width):
return length * width

max(area(3.3, 4.2), area(4.5, 3.1))

Execution Order:

1️. area(3.3, 4.2) → 13.86


2️. area(4.5, 3.1) → 13.95
3️. max(13.86, 13.95) → 13.95

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:

All three ratings must be integers (int)


Each rating must be between 1 and 5 (inclusive)

If a rating is 0 or 6, it violates the contract!


4. Test Cases for is_palindrome(s)
Test Cases:

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.

5. Global vs. Local Variables


Key Rules:

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!).

Example 1: Using a Global Variable


a = 3
def foo(b):
c = b + a # Uses global 'a'
return c
d = foo(5) # d = 5 + 3 = 8

Example 2: Modifying a Global (Bad Practice)


a = 3
def foo():
global a
a = 5 # Changes global 'a'!
foo()
print(a) # Output: 5

Best Practice: Pass globals as arguments instead of modifying them inside functions.

6. Memory Model
How Python Stores Data:

• Global Variables: Stored in the main frame


• Local Variables: Stored in function-specific frames

Example:
def foo():
x = 1 # Local variable

foo()
print(x) # Error! 'x' is local to foo().

Memory Visualization:

Before foo() is called:

[main frame]
- Variables: None

During foo() execution:

[foo frame]
- x: 1

After foo() finishes:

• foo frame is deleted.


7. Complicated Memory Models
Function Calling Another Function:
def foo_1(b):
b += foo_2(b)
return b

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.

Recursion & Stack Overflow Example:

def foo():
foo() # Calls itself infinitely!

foo() # Crash! Stack overflow.

Why? Each recursive call adds a new frame to the stack. Without a base case, the stack fills
up!

8. Coding Style Tips


Avoid Global Variables: Pass them as arguments instead.

def calculate(b, a): # 'a' is passed in


return b + a

Replace Magic Numbers:

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

You might also like