0% found this document useful (0 votes)
4 views6 pages

Python Module2 Notes

The document provides a comprehensive overview of Python programming concepts, including functions, loops, lists, dictionaries, string methods, file I/O, exception handling, and object-oriented programming (OOP). It covers key features such as defining functions, using loops, manipulating lists and dictionaries, handling exceptions, and creating classes and objects. The document emphasizes best practices and provides examples for clarity.

Uploaded by

machariae513
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)
4 views6 pages

Python Module2 Notes

The document provides a comprehensive overview of Python programming concepts, including functions, loops, lists, dictionaries, string methods, file I/O, exception handling, and object-oriented programming (OOP). It covers key features such as defining functions, using loops, manipulating lists and dictionaries, handling exceptions, and creating classes and objects. The document emphasizes best practices and provides examples for clarity.

Uploaded by

machariae513
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

Python

Continuing from— Module


variables, 2if Notes
data types & statements
Functions · Loops · Lists · Dicts · String Methods · File I/O · Exceptions · OOP

1 Functions
A function is a reusable block of code that performs a task. Define it once, call it many times.

# Define a function

def greet(name):

return "Hello, " + name

# Call the function

print(greet("Alice")) # Hello, Alice

Default parameters Multiple return values

def greet(name, msg='Hi'): def min_max(lst):

return f"{msg}, {name}" return min(lst), max(lst)

greet("Bob") # Hi, Bob low, high = min_max([3,1,9,4])

greet("Bob", "Hey") # Hey, Bob # low=1, high=9

*args and **kwargs

def add_all(*numbers): # accepts any number of args

return sum(numbers)

add_all(1, 2, 3, 4) # -> 10

def show_info(**details): # keyword arguments

for key, val in [Link]():

print(f"{key}: {val}")

show_info(name="Ana", age=20)

Lambda functions (anonymous)

square = lambda x: x ** 2

print(square(5)) # 25

nums = [3, 1, 4, 1, 5]

[Link](key=lambda x: -x) # sort descending


Tip: keep functions short and focused — one function should do one thing well.

2 Loops
Loops let you repeat code. Python has two types: for (iterating over a sequence) and while (repeat while a
condition is true).

for loop while loop

for i in range(5): count = 0

print(i) # 0 1 2 3 4 while count < 5:

print(count)
fruits = ["apple", "mango"]
count += 1
for fruit in fruits:

print(fruit) # prints 0 1 2 3 4

Loop control: break, continue, else

for n in range(10):

if n == 3: continue # skip 3

if n == 7: break # stop at 7

print(n) # 0 1 2 4 5 6

else:

print("loop finished") # runs if no break

enumerate() and zip()

colors = ["red", "green", "blue"]

for i, color in enumerate(colors):

print(f"{i}: {color}") # 0: red, 1: green ...

names = ["Alice", "Bob"]

ages = [25, 30]

for name, age in zip(names, ages):

print(f"{name} is {age}")

List comprehension (compact loop)

squares = [x**2 for x in range(5)] # [0, 1, 4, 9, 16]

evens = [x for x in range(10) if x % 2 == 0] # [0,2,4,6,8]


3 Lists & Tuples

List — mutable (changeable)


Tuple — immutable (fixed)
nums = [10, 20, 30]
point = (3, 5)
[Link](40) # add end
x, y = point # unpack
[Link](1, 15) # insert at 1
# tuples can't be changed
[Link](20) # remove value
# point[0] = 1 <- ERROR
[Link]() # remove last

[Link]() # sort in place # use for fixed data:

len(nums) # length RGB = (255, 128, 0)

Slicing

lst = [0, 1, 2, 3, 4, 5]

lst[1:4] # [1, 2, 3] -- index 1 up to (not including) 4

lst[:3] # [0, 1, 2] -- from start

lst[3:] # [3, 4, 5] -- to end

lst[::2] # [0, 2, 4] -- every 2nd element

lst[::-1] # [5,4,3,2,1,0] -- reversed

Remember: list indices start at 0. Negative indices count from the end: lst[-1] is the last element.

4 Dictionaries
A dictionary stores key-value pairs. Keys must be unique. Very useful for structured data.

student = {"name": "Alice", "age": 20, "grade": "A"}

# Access

student["name"] # "Alice"

[Link]("score", 0) # 0 (safe -- no KeyError)

# Modify

student["age"] = 21 # update

student["school"] = "UoN" # add new key

del student["grade"] # delete key

# Iterate

for key, value in [Link]():


print(f"{key} -> {value}")

.keys() .values() .items() .update() .pop(key) "key" in dict

Sets (bonus — like a dict with only keys)

# duplicates automatically removed

fruits = {"apple", "mango", "apple"} # -> {"apple", "mango"}

a = {1,2,3}; b = {2,3,4}

a & b # intersection: {2, 3}

a | b # union: {1, 2, 3, 4}

a - b # difference: {1}

5 String Methods

s = " Hello, World! "

[Link]() # "Hello, World!" -- remove whitespace

[Link]() # " hello, world! "

[Link]() # " HELLO, WORLD! "

[Link]("World", "Python") # " Hello, Python! "

[Link](",") # [" Hello", " World! "]

[Link](" H") # True

[Link]("World") # index of first match (or -1)

" ".join(["a","b","c"]) # "a b c"

f-strings (formatted strings)

name = "Alice"; score = 95.6

print(f"{name} scored {score:.1f}%") # Alice scored 95.6%

print(f"{2 ** 10}") # 1024 (expressions work!)

6 File I/O
Reading from and writing to files. Always use 'with' — it automatically closes the file even if an error
occurs.
Reading a file
Writing a file
with open("[Link]", "r") as f:
with open("[Link]", "w") as f:
content = [Link]() # whole file
[Link]("Hello\n")

[Link]("World\n") with open("[Link]") as f:

# "w" = write (overwrites) for line in f: # line by line

# "a" = append (adds to end) print([Link]())

"r" read "w" write "a" append "rb" binary .read() .readlines()

.writelines()

7 Exception Handling
Errors (exceptions) crash your program. Use try/except to handle them gracefully.

try:

num = int(input("Enter a number: "))

result = 10 / num

except ValueError:

print("That's not a valid number!")

except ZeroDivisionError:

print("Can't divide by zero!")

else:

print(f"Result: {result}") # runs if no exception

finally:

print("Done.") # always runs

ValueError TypeError IndexError KeyError FileNotFoundError ZeroDivisionError

Avoid bare except: — it catches everything including system errors. Always specify the exception type.

8 OOP Basics — Classes & Objects


Object-Oriented Programming groups related data and functions into a class. An object is an instance of a
class.

class Student:

def __init__(self, name, age): # constructor

[Link] = name

[Link] = age
[Link] = []

def add_grade(self, grade): # method

[Link](grade)

def average(self):

return sum([Link]) / len([Link])

def __str__(self): # string representation

return f"Student: {[Link]}"

# Create objects

s1 = Student("Alice", 20)

s1.add_grade(88)

s1.add_grade(92)

print([Link]()) # 90.0

print(s1) # Student: Alice

Inheritance

class GradStudent(Student): # inherits from Student

def __init__(self, name, age, thesis):

super().__init__(name, age) # call parent __init__

[Link] = thesis

def __str__(self): # override parent method

return f"Grad: {[Link]}, Thesis: {[Link]}"

The four pillars of OOP: Encapsulation, Inheritance, Polymorphism, Abstraction. You just learned the first two!

You might also like