Main Function Pattern
- main serves as the entry point for a script
Fundamentals of Python: First Programs
Some examples:
Expressions are also included:
['I', "'", 'm', ' ', 'a', ' ', 'b', 'a', 'd', 'd', 'i', 'e', ' ', 'b', 'a', 'b', 'y', ',', ' ', 't', 'h', 'a', 't', "'", 's', ' ', 'h', 'o', 'w', ' ', 'm', 'y', ' ', 'm', 'o', 'm', 'm', 'y', ' ', 'm', 'a', 'd', 'e', ' ', 'm', 'e']
Before for loop: [2, 3, 4, 5]
After for loop: [4, 9, 16, 25]
Before for loop: ['Anyone', 'know', 'if', 'the', 'student', 'center', 'is', 'open', 'twenty', 'four', 'seven?']
After for loop: ['ANYONE', 'KNOW', 'IF', 'THE', 'STUDENT', 'CENTER', 'IS', 'OPEN', 'TWENTY', 'FOUR', 'SEVEN?']
Suppose you have a list L with another list aList
| List Methods | What it Does |
|---|---|
L.append(element)
|
Adds element to the end of L |
L.extend(aList)
|
Adds the elements of aList to the end of L |
L.insert(index, element)
|
Inserts element at index if index is less than the length of L. Otherwise, inserts element at the end of L. |
L.pop()
|
Removes and returns the element at the end of L. |
L.pop(index)
|
Removes and returns the element at index |
Before using .insert() [1, 2]
After using .insert() [1, 10, 2]
After using .insert() again [1, 10, 2, 25]
Before sorting: [4, 2, 10, 8]
After sorting: [2, 4, 8, 10]
Mutable property of lists leads to interesting phenomena:
[10, 20, 30]
[10, 20, 30]
[10, 99, 30]
[10, 99, 30]
To prevent aliasing, create a new object and copy contents of original:
[10, 99, 30]
[10, 99, 30]
[10, 100, 30]
[10, 99, 30]
.copy() also works
def <function name>(<parameter-1>, ..., <parameter-n>):
<body>
{'Savannah': '476-3321', 'Nathaniel': '351-7743'}
{'Name': 'Molly', 'Age': 18}
{}
[][] also to replace a value at an existing key[] to obtain the value associated with a keyBefore pop: {'name': 'Sandy', 'occupation': 'manager', 'age': 25}
Popped value: manager
After pop: {'name': 'Sandy', 'age': 25}
Result: None
name Sandy
occupation manager
age 25
items() method:| Operation | What It Does |
|---|---|
len(d)
|
Returns the number of entries |
d[key]
|
Insert/replace/access value |
d.get(key [, default])
|
Returns value if key exists, else default |
d.pop(key [, default])
|
Removes key and returns value, else default |
list(d.keys())
|
Returns a list of keys |
list(d.values())
|
Returns a list of values |
list(d.items())
|
Returns a list of (key, value) tuples |
d.clear()
|
Removes all entries |
hexToBinaryTable = {
'0': '0000', '1': '0001', '2': '0010', '3': '0011',
'4': '0100', '5': '0101', '6': '0110', '7': '0111',
'8': '1000', '9': '1001', 'A': '1010', 'B': '1011',
'C': '1100', 'D': '1101', 'E': '1110', 'F': '1111'
}
def convert(number, table):
"""Builds and returns the base two representation of number."""
binary = ""
for digit in number:
binary = binary + table[digit]
return binary
print(convert("35A", hexToBinaryTable))
print(convert("F", hexToBinaryTable))001101011010
1111
# Sample data (in practice, this would come from a file)
words = ["apple", "banana", "apple", "orange", "banana", "apple", "grape"]
# Build frequency dictionary
theDictionary = {}
for word in words:
word = word.upper()
number = theDictionary.get(word, None)
if number == None:
theDictionary[word] = 1
else:
theDictionary[word] = number + 1
print("Frequency dictionary:", theDictionary)Frequency dictionary: {'APPLE': 3, 'BANANA': 2, 'ORANGE': 1, 'GRAPE': 1}
| Scenario | Best Choice | Why? |
|---|---|---|
| Ordered sequence of items | List | Position matters |
| Need to look up by key | Dictionary | Fast key-based lookup |
| Shopping list | List | Simple sequence |
| Phone book | Dictionary | Look up by name |
| Student grades | Dictionary | Look up by student ID |
| Steps in a recipe | List | Order matters |
| Word frequency counter | Dictionary | Word → count mapping |
list_name[row][column] (both start at 0)First row: [1, 2, 3]
First element: 1
Middle element: 5
After modification:
[1, 2, 3]
[4, 99, 6]
[7, 8, 9]
matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
print("All elements with indices:")
for row in range(len(matrix)): # For each row
for col in range(len(matrix[row])): # For each column
print(f"matrix[{row}][{col}] = {matrix[row][col]}")
print("\nDisplay as grid:")
for row in matrix:
for val in row:
print(f"{val:3}", end="")
print() # New line after each rowAll elements with indices:
matrix[0][0] = 1
matrix[0][1] = 2
matrix[0][2] = 3
matrix[1][0] = 4
matrix[1][1] = 5
matrix[1][2] = 6
matrix[2][0] = 7
matrix[2][1] = 8
matrix[2][2] = 9
Display as grid:
1 2 3
4 5 6
7 8 9
Zeros matrix:
[0, 0, 0]
[0, 0, 0]
[0, 0, 0]
Identity matrix:
[1, 0, 0, 0]
[0, 1, 0, 0]
[0, 0, 1, 0]
[0, 0, 0, 1]
# Rows = students, Columns = assignments
grades = [
[95, 87, 92], # Student 0
[78, 85, 91], # Student 1
[88, 92, 89], # Student 2
]
# Calculate average for each student
for i in range(len(grades)):
total = sum(grades[i])
average = total / len(grades[i])
print(f"Student {i}: average = {average:.1f}")
# Calculate average for each assignment
for j in range(len(grades[0])):
total = 0
for i in range(len(grades)):
total += grades[i][j]
average = total / len(grades)
print(f"Assignment {j}: average = {average:.1f}")Student 0: average = 91.3
Student 1: average = 84.7
Student 2: average = 89.7
Assignment 0: average = 87.0
Assignment 1: average = 88.0
Assignment 2: average = 90.7
# WRONG way - creates references to the same row
wrong = [[0] * 3] * 3
print("Wrong initialization:")
for row in wrong:
print(row)
# Modifying one row affects all rows!
wrong[0][0] = 99
print("\nAfter modification:")
for row in wrong:
print(row)
# RIGHT way - create independent rows
correct = [[0 for col in range(3)] for row in range(3)]
print("\nCorrect initialization:")
correct[0][0] = 99
for row in correct:
print(row)Wrong initialization:
[0, 0, 0]
[0, 0, 0]
[0, 0, 0]
After modification:
[99, 0, 0]
[99, 0, 0]
[99, 0, 0]
Correct initialization:
[99, 0, 0]
[0, 0, 0]
[0, 0, 0]
Grade Book:
Alice: scores [95, 87, 92], average 91.3
Bob: scores [78, 85, 91], average 84.7
Charlie: scores [88, 92, 89], average 89.7
[] to add/access dictionary entries