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: This note contains all information about python programmin
Description: This note contains all information about python programmin
Document Preview
Extracts from the notes are below, to see the PDF you'll receive please use the links above
PYTHON FULL NOTES
For all students
Definition
Python is a high-level, object-oriented programming language that’s used for many tasks,
including web development, data analysis, and machine learning
...
What Python is used for?
Web development: Python is used to create web applications on a server
...
Machine learning: Python is used to build machine learning models
...
System scripting: Python is used to automate tasks
...
Portable
Python can run on many different platforms, including Windows, Linux, and macOS
...
Who created Python?
Guido van Rossum created Python in 1991
...
Variables
In Python, variables are used to store data values
...
You create a variable simply by assigning a value to it:
Python
x = 10
name = “Alice”
Naming rule
Variable names can contain letters, digits, and underscores (_)
...
Variable names are case-sensitive (myVar and myvar are different variables)
...
g
...
Types of Variables:
Python is dynamically typed, meaning the type of a variable is determined at runtime
...
Common data types include:
int: Integers (e
...
, x = 10)
float: Floating-point numbers (e
...
, pi = 3
...
g
...
g
...
g
...
Global variables: Defined outside of any function and accessible from anywhere in the program
...
Example:
x = 10 # Global variable
def my_function():
y = 5 # Local variable
print(x) # Access global variable
print(y) # Access local variable
my_function()
Point:
Python is case-sensitive, so myVar and MyVar are different variables
...
Classes in python
In Python, a class is a blueprint for creating objects
...
Defining a Class
To define a class, you use the class keyword followed by the class name and a colon
...
Example:
Class Dog:
def __init__(self, name, breed):
self
...
breed = breed
def bark(self):
print(“Woof!”)
Explanation
Class Dog:: This line defines a class named Dog
...
It gets called when you create a
new object (instance) of the class
...
Self
...
Self
...
Def bark(self):: This is a method that defines the behavior of the Dog object
...
Creating object
To create an object of a class, you call the class name like a function, passing any necessary
arguments to the constructor
...
Example
Print(my_dog
...
breed) # Output: Labrador
my_dog
...
Example: 5, -10, 100
String (str):
A sequence of characters enclosed within single, double, or triple quotes
...
Here’s a breakdown of different types of operators:
1
...
Comparison Operators:
== : Equal to
!= : Not equal to
> : Greater than
< : Less than
>= : Greater than or equal to
<= : Less than or equal to
3
...
Logical Operators:
and : Returns True if both operands are True
or : Returns True if at least one operand is True
not : Inverts the logical state of the operand
5
...
g
...
Identity Operators:
is : Checks if two objects are the same object (memory location)
is not : Checks if two objects are not the same object
Python has several built-in data type:
Numeric Types:
int: Represents integers (whole numbers), e
...
, 1, 2, -10
...
g
...
14, -2
...
complex: Represents complex numbers, e
...
, 2 + 3j
...
g
...
List: Represents ordered, mutable (changeable) collections of items, e
...
, [1, 2, “three”]
...
g
...
Range: Represents a sequence of numbers, e
...
, range(1, 5)
...
g
...
Set Types:
set: Represents an unordered collection of unique items, e
...
, {1, 2, 3}
...
g
...
Boolean Type:
bool: Represents a Boolean value (True or False), e
...
, True
...
g
...
Bytearray: Represents a mutable sequence of bytes, e
...
, bytearray(b”Hello”)
...
If else statement
In Python, if-else statements are used for conditional execution of code
...
Syntax :
If condition:
# code to execute if the condition is true
else:
# code to execute if the condition is false
Example
X = 10
if x > 5:
print(“x is greater than 5”)
else:
print(“x is not greater than 5”)
Explanation of if else statement
An if-else statement is a conditional statement that executes a specific block of code if a given
condition is true, or another block of code if the condition is false
...
If the condition is true, the code in the if block is executed
...
Examples
Weather: If it rains, you use an umbrella, otherwise you don’t
...
Time of day: A program can create a greeting based on the time of day
...
Languages that support if-else statements C, C++, Java, JavaScript, and Python
...
If condition:
# code to execute if the condition is true
2
...
if-elif-else statement:
If condition1:
# code to execute if condition1 is true
elif condition2:
# code to execute if condition2 is true
else:
# code to execute if none of the above conditions are true
4
...
Ternary Operator (Short-hand if-else):
Value_if_true if condition else value_if_false
Boolean value
In Python, a boolean value represents one of two possible states: True or False
...
Representing Boolean Values:
The keywords True and False are used to represent boolean values
...
2
...
g
...
They are also used in logical expressions that involve comparison operators (==, !=, <, >, <=, >=)
and logical operators (and, or, not)
...
Converting to Boolean Values:
You can use the bool() function to convert other data types into boolean values
...
0)
Empty sequences ([], (), “”, {})
The special value None
Example
Print(bool(1))
# True
print(bool(“Hello”)) # True
print(bool([]))
# False
print(bool(0))
# False
Comparison operation
Comparison operators in Python are used to compare two values and return a Boolean value (True or False)
...
Here’s an
example:
X = 10
if x > 5:
print(“x is greater than 5”)
if x > 8:
print(“x is also greater than 8”)
else:
print(“x is not greater than 8”)
Explanation
The outer if statement checks if x is greater than 5
...
If the second condition is also true, the code inside the inner if block executes
...
Another example with elif:
Num = 15
if num > 0:
print(“Number is positive”)
if num % 2 == 0:
print(“Number is even”)
else:
print(“Number is odd”)
else:
print(“Number is not positive”)
Elif statement
In Python, the elif statement stands for “else if”
...
Here’s how it works:
Syntax:
If condition1:
# code to execute if condition1 is true
elif condition2:
# code to execute if condition1 is false and condition2 is true
elif condition3:
# code to execute if both condition1 and condition2 are false and condition3 is true
...
Python will evaluate the conditions in order, and execute the code block associated with the
first true condition
...
If you only need to check one condition, you can use a simple if statement
...
For loop statement
A for loop in Python is used to iterate over a sequence (like a list, tuple, string, or range) or other iterable object
...
Item:
A variable that takes on the value of each element in the sequence during the loop
...
Nested for loop statement
In Python, a nested for loop is a loop that is placed inside another loop
...
Syntex:
For outer_variable in outer_sequence:
# Code to execute in the outer loop
for inner_variable in inner_sequence:
# Code to execute in the inner loop
Example
For i in range(1, 4): # Outer loop
for j in range(1, 4): # Inner loop
print(i, j)
Output
11
12
13
21
22
23
31
32
33
Explanation:
The outer loop iterates over the range 1, 4, which means it will take the values 1, 2, and 3
...
This results in a total of 9 iterations (3 iterations of the outer loop * 3 iterations of the inner loop for
each outer iteration)
...
Syntax:
While condition:
# code to be executed
How it works:
The loop starts by evaluating the condition
...
After the code block is executed, the condition is evaluated again
...
Example
Count = 1
while count <= 5:
print(count)
count += 1
This code will print the numbers 1 through 5
...
Collection module in python
The collections module in Python provides specialized container data types that go beyond the builtin lists, dictionaries, sets, and tuples
...
namedtuple:
Creates a tuple-like object where each element has a name, improving code readability
...
From collections import namedtuple
Point = namedtuple(‘Point’, [‘x’, ‘y’])
p = Point(1, 2)
print(p
...
y) # Output: 1 2
2
...
Prevents Key Error exceptions and simplifies code when working with dictionaries
...
OrderedDict:
A dictionary that remembers the order in which keys were inserted
...
From collections import OrderedDict
d = OrderedDict()
d[‘a’] = 1
d[‘b’] = 2
print(d
...
Counter:
A dictionary subclass that counts the occurrences of hashable objects
...
From collections import Counter
c = Counter(‘hello world’)
print(c[‘l’]) # Output: 3
5
...
Useful for implementing stacks, queues, and other data structures
...
append(4)
d
...
Use defaultdict to avoid Key Error exceptions and provide default values
...
Use Counter to count the occurrences of items in a sequence
...
Function
In Python, a function is a block of reusable code that performs a specific task
...
Here’s how you define a function in
Def function_name(parameters):
“””docstring”””
# code to be executed
return value
Explanation:
def: The keyword used to define a function
...
Parameters (optional): Input values that the function can accept
...
Code to be executed: The body of the function containing the instructions to perform the task
...
Example:
Def greet(name):
“””This function greets the user
...
Built-in Functions:
These are readily available functions within Python itself, like print(), len(), type(), etc
...
User-defined Functions:
These are functions created by the user to perform specific tasks
...
Lambda Functions:
Anonymous functions, defined using the lambda keyword, typically for short, simple operations
...
Recursive Functions:
Functions that call themselves to solve a problem
...
Higher-Order Functions:
Functions that take other functions as arguments or return functions as results
Def apply_twice(func, x):
return func(func(x))
6
...
My_list = [1, 2, 3]
my_list
...
Here’s what you need to know:
Purpose: The return statement marks the end of a function’s execution and specifies the value or values to pass back to
the part of the code that called the function
...
Multiple Return Values: You can return multiple values from a function by separating them with
commas:
Def get_name_and_age():
return “Alice”, 30
name, age = get_name_and_age()
print(name) # Output: Alice
print(age) # Output: 30
In Python:
Class: A blueprint for creating objects
...
Think of it like a
template or a mold
...
It is the realization of the blueprint, representing a specific entity with its own data and behavior
...
It defines the characteristics of a car like the number of wheels, the engine type, the color, etc
...
Each car object can have different colors, engine types, etc
...
Example
Class Dog:
def __init__(self, name, breed):
self
...
breed = breed
def bark(self):
print(“Woof!”)
# Creating objects
dog1 = Dog(“Buddy”, “Golden Retriever”)
dog2 = Dog(“Max”, “Labrador”)
# Accessing attributes and methods
print(dog1
...
bark()
# Output: Woof!
Inheritance
Inheritance in Python is a mechanism that allows a class (child class or derived class) to inherit
attributes and methods from another class (parent class or base class)
...
Key points about inheritance in Python:
Parent class: The class that provides the attributes and methods to be inherited
...
Code reusability: Child classes can use the code from the parent class, avoiding redundancy and
improving code organization
...
Super() function: Used to access methods and attributes of the parent class from within the child
class
...
Example
Class Animal:
def __init __(self, name):
self
...
name) # Output: Buddy
dog
...
name) # Output: Whiskers
cat
...
This promotes code reusability and establishes a hierarchy of classes
...
Single Inheritance :
A child class inherits from only one parent class
...
Python
class Animal:
def speak(self):
print(“Animal speaks”)
class Dog(Animal):
def bark(self):
print(“Dog barks”)
dog = Dog()
dog
...
bark()
2
...
This allows a class to combine functionalities from different classes
...
fly() # Inherited from Flyer
duck
...
Multilevel Inheritance:
A child class inherits from a parent class, which in turn inherits from another parent class, creating a chain of inheritance
...
speak() # Inherited from Animal
dog
...
bark()
4
...
This allows you to create a specialized hierarchy of classes
...
move() # Inherited from Vehicle
bike = Bike()
bike
...
Hybrid Inheritance:
A combination of two or more of the above types of inheritance
...
It’s particularly useful when
working with inheritance in object-oriented programming
...
class Parent:
def greet(self):
print(“Hello from Parent!”)
class Child(Parent):
def greet(self):
super()
...
greet()
Output
Hello from Parent!
Hello from Child!
Benefits of using super():
Avoids explicitly naming the parent class:
This makes your code more maintainable and flexible, especially when dealing with multiple
inheritance
...
Key Points:
super() is a built-in function that returns a temporary object of the parent class
...
Super() is especially useful when you want to extend the functionality of a parent class method
without completely reimplementing it
...
It allows you to write code that can work with objects of different types
without needing to know their exact type beforehand
...
A subclass can provide its own
implementation of a method that is already defined in its parent class
...
Duck Typing:
Python is dynamically typed, which means the type of a variable is determined at runtime
...
This is often referred to as “duck typing”
...
For example, the len() function works on strings, lists, tuples, and other sequence types
...
speak())
dog = Dog()
cat = Cat()
animal_sound(dog) # Output: Woof!
Animal_sound(cat) # Output: Meow!
Access modifiers
In Python, access modifiers control the accessibility of class members (attributes and methods)
...
Instead, it uses naming
conventions to indicate the intended access level:
1
...
This means they can be accessed from anywhere, both inside and outside the class
...
public_attribute = value
def public_method(self):
print(“Public method”)
2
...
It’s a convention that suggests the member should be treated as non-public, but it can still be accessed from within the class and its subclasses
...
_protected_attribute = value
def _protected_method(self):
print(“Protected method”)
3
...
Python performs name mangling on private members, making them harder to access directly from outside the class
...
Python
class MyClass:
def __init__(self, value):
self
...
It allows you to store and retrieve data from external sources, such as text
files, CSV files, and databases
...
You need to specify the file path and the mode in which
you want to open the file (e
...
, read, write, append)
...
Writing to a file:
Use methods like write() or writelines() to add content to the file
...
Example:
# Open a file for writing
with open(“myfile
...
write(“Hello, world!\n”)
# Open a file for reading
with open(“myfile
...
read()
print(content)
Thank you
Title: Python
Description: This note contains all information about python programmin
Description: This note contains all information about python programmin