Search for notes by fellow students, in your own course and all over the country.
Browse our notes for titles which look like what you need, you can preview any of the notes via a sample of the contents. After you're happy these are the notes you're after simply pop them into your shopping cart.
Title: python
Description: python class notes. only learn these notes more then sufficient.
Description: python class notes. only learn these notes more then sufficient.
Document Preview
Extracts from the notes are below, to see the PDF you'll receive please use the links above
1
...
append(5)
my_list
...
remove(3)
element = my_list
...
clear()
Other List Methods
my_list
...
reverse()
my_list
...
Tuples
Creating a Tuple
my_tuple = (1, 2, 3, 'a', 'b')
Accessing Elements
print(my_tuple[1])
es
# Remove element with value 3
# Remove and return element at index 2
# Remove all elements
# Output: 2
Slicing
print(my_tuple[1:3])
# Output: (2, 3)
Tuple Unpacking
a, b, c = (1, 2, 3)
# Assign 1 to a, 2 to b, 3 to c
Tuple Methods
my_tuple
...
index('a')
# Count occurrences of 1
# Find the index of 'a'
Note: Tuples are immutable, meaning elements cannot be modified after creation
...
Sets
Creating a Set
e_
my_set = {1, 2, 3, 'a'}
Adding/Removing Elements
my_set
...
remove(2)
my_set
...
isdisjoint(set2)
set1
...
Dictionaries
Creating a Dictionary
my_dict = {"name": "John", "age": 25, "city": "New York"}
Accessing Elements
print(my_dict["name"])
print(my_dict
...
com"
my_dict["age"] = 26
# Add new key-value pair
# Modify existing value
Removing Elements
del my_dict["city"]
my_dict
...
clear()
De
# Delete the key-value pair 'city'
# Remove and return value of 'email'
# Remove all elements
Iterating Over a Dictionary
e_
for key, value in my_dict
...
keys()
my_dict
...
items()
cod
# Get all keys
# Get all values
# Get all key-value pairs
2
...
Creating a Class
class MyClass:
def __init__(self, name):
self
...
name}!")
# Creating an object (instance of MyClass)
obj = MyClass("Alice")
obj
...
class Person:
def __init__(self, name, age):
self
...
age = age
2
...
class Employee:
company = "Google"
# Class attribute
def __init__(self, name):
self
...
company) # Output: Google
print(emp2
...
e_
emp1
...
company) # Output: Amazon
print(emp2
...
Methods
Instance Methods
Operate on object instances
...
name = name
cod
def bark(self):
# Instance method
print(f"{self
...
Use @classmethod
...
species}")
Static Methods
Do not depend on instance or class attributes
...
class Utility:
@staticmethod
def add(a, b):
return a + b
print(Utility
...
Inheritance
Basic Inheritance
Allows one class to inherit the attributes and methods of another class
...
name = name
De
def speak(self):
print(f"{self
...
")
e_
class Dog(Animal):
# Dog inherits from Animal
def speak(self):
print(f"{self
...
")
dog = Dog("Buddy")
dog
...
super()
Function
Calls the parent class's methods
...
__init__(name)
# Call parent class constructor
self
...
Encapsulation
Public, Protected, and Private Attributes
Public Attributes: Accessible anywhere
...
brand = brand # Public attribute
Protected Attributes: Indicated by a single underscore _, meant for internal use, but
still accessible
...
_brand = brand # Protected attribute
Private Attributes: Indicated by double underscore __, not accessible directly
...
__brand = brand # Private attribute
Accessing Private Attributes (Name Mangling)
car = Car("Tesla")
print(car
...
Polymorphism
De
Method Overriding
Redefining a method in a derived class that exists in the parent class
...
14 * self
...
Focuses on methods rather than inheritance
...
sound()
animal_sound(Dog())
animal_sound(Cat())
# Output: Bark
# Output: Meow
7
...
Use abc module to define abstract classes
...
sound()
# Must implement abstract method
# Output: Bark
8
...
method_a()
obj
...
FUNCTIONS
Defining a Function
Basic Syntax
def function_name(parameters):
# function body
return result
Example
def greet(name):
return f"Hello, {name}!"
print(greet("Alice"))
# Output: Hello, Alice!
2
...
def add(a, b):
return a + b
add(2, 3)
# Output: 5
Keyword Arguments
Passed by name during function call
...
"
De
describe(age=25, name="Alice")
# Output: Alice is 25 years old
...
def greet(name, message="Hello"):
return f"{message}, {name}!"
greet("Alice")
greet("Alice", "Hi")
cod
# Output: Hello, Alice!
# Output: Hi, Alice!
3
...
def add(*args):
return sum(args)
add(1, 2, 3, 4)
**kwargs
# Output: 10
(Keyword Variable-Length)
Allows passing multiple keyword arguments
...
Scope
# Output: Hi, Bob!
es
Local Scope
Variables defined within a function are local to that function
...
# Global variable
De
def my_func():
print(x) # Accessing global variable
my_func()
# Output: 20
e_
Using global Keyword
Modify global variables inside a function
...
Returning Values
cod
Returning a Single Value
def square(x):
return x ** 2
result = square(4)
# Output: 16
Returning Multiple Values
def coordinates():
return (1, 2, 3)
x, y, z = coordinates()
6
...
De
7
...
def add(*args):
return sum(args)
print(add(1, 2, 3))
# Output: 6
Using **kwargs
cod
Accepts a variable number of keyword arguments
...
items():
print(f"{key}: {value}")
greet(name="Alice", age=25)
es
# Output: name: Alice, age: 25
8
...
python
Copy code
list(map(lambda x: x * 2, [1, 2, 3]))
filter():
# Output: [2, 4, 6]
Filter items based on a condition
...
python
Copy code
sorted([3, 1, 2])
# Output: [1, 2, 3]
4
...
close()
2
...
Reading Files
Reading Entire File:
cod
with open("file
...
read()
print(content)
Reading Line by Line:
with open("file
...
with open("file
...
readline()
print(line)
readlines():
Returns a list of lines
...
txt", "r") as file:
lines = file
...
Writing Files
Writing with 'w' (Overwrites):
with open("file
...
write("Hello, world!")
Appending with 'a':
with open("file
...
write("\nAdding a new line
...
File Object Methods
De
file
...
file
...
file
...
file
...
e_
6
...
bin", "wb") as file:
file
...
bin", "rb") as file:
data = file
...
Checking if File Exists
Using os module:
import os
if os
...
exists("file
...
Exception Handling
1
...
Catching Multiple Exceptions
Using Multiple except Blocks:
De
try:
x = int(input("Enter a number: "))
y = 1 / x
except ValueError:
print("That's not a number!")
except ZeroDivisionError:
print("You cannot divide by zero!")
e_
Using Single except Block:
try:
cod
x = int(input("Enter a number: "))
y = 1 / x
except (ValueError, ZeroDivisionError) as e:
print(f"Error occurred: {e}")
3
...
txt", "r")
# Some code that may raise an exception
except FileNotFoundError:
print("File not found")
finally:
file
...
Else Block
es
The finally block runs no matter what happens in the try block:
Runs if no exceptions occur:
try:
file = open("file
...
close()
5
...
Custom Exceptions
Creating a Custom Exception:
class MyError(Exception):
pass
De
def check_value(value):
if value < 0:
raise MyError("Value cannot be negative")
try:
check_value(-1)
except MyError as e:
print(e)
e_
Modules and Packages
1
...
Accessing Module Content
Calling functions from imported module:
python
es
Copy code
import math
result = math
...
0
Importing multiple functions:
python
Copy code
from math import sqrt, ceil
result = ceil(sqrt(10))
List of all functions and attributes of a module:
python
Copy code
import module_name
print(dir(module_name))
De
3
...
py file:
python
Copy code
# In my_module
...
greet("John")
4
...
py
module1
...
py
Importing a module from a package:
python
Copy code
from my_package import module1
Importing specific functions or classes:
es
python
Copy code
from my_package
Title: python
Description: python class notes. only learn these notes more then sufficient.
Description: python class notes. only learn these notes more then sufficient.