Python Notes
Python Notes
InsideAIML
• Compiler: Python uses a compiler to convert its source code into byte-
code. This bytecode is a lower-level representation of the code.
1
3 Scientific Computing
Scientific computing is the use of computer algorithms, mathematical models,
and numerical methods to solve scientific and engineering problems. It encom-
passes tasks like data analysis, simulation, modeling, and optimization. This
field is crucial in various domains such as physics, chemistry, biology, engineer-
ing, and economics, where computational methods help solve complex problems
INSIDEAIML
efficiently.
jupyter notebook
2
• Variables: Variables are used to store data values and are assigned using
the ‘=‘ operator.
• Memory: Python manages memory automatically, allocating memory
for variables and objects and releasing it when no longer needed through
a process called garbage collection.
• Space Management: Python provides tools for managing memory and
INSIDEAIML
resources efficiently. You can use libraries like ‘numpy‘ for optimized mem-
ory usage in numerical computations.
article enumitem
Python Basics Notes Your Name October 29, 2023
8 Formatted String
Formatted strings allow you to embed expressions inside string literals, using
curly braces {} and the format() method.
Example:
name = "Alice"
age = 30
print(f"My name is {name} and I am {age} years old.")
9 Data Types
Python supports various data types, including:
• int: Integer numbers (e.g., 5, -42)
• float: Floating-point numbers (e.g., 3.14, -0.001)
• str: Strings (e.g., ”Hello, World!”)
• bool: Boolean values (True or False)
• list: Ordered collection of items (e.g., [1, 2, 3])
• tuple: Ordered, immutable collection (e.g., (1, 2, 3))
• dict: Key-value pairs (e.g., ”name”: ”Alice”, ”age”: 30)
3
10 Checking the Data Type
You can check the data type of a variable using the type() function.
Example:
x = 42
print(type(x)) # Output: <class ’int’>
11 INSIDEAIML
Type Conversion
You can convert between data types using type-specific functions (e.g., int(),
str(), float()).
Example:
x = "5"
y = int(x) # Convert string to integer
print(y) # Output: 5
12 Shortcuts
Python offers shortcuts for common operations, such as += for addition and
assignment.
Example:
x = 5
x += 3 # Equivalent to x = x + 3
print(x) # Output: 8
13 Examples
Here are some examples demonstrating the concepts discussed above:
4
13.3 Data Types and Type Conversion
x = 42
y = 3.14
z = "Hello"
is_true = True
my_list = [1, 2, 3]
my_dict = {"name": "Alice", "age": 30}
INSIDEAIML
print(type(x)) # Output: <class ’int’>
print(float(x)) # Convert int to float
print(str(x)) # Convert int to str
13.4 Shortcuts
x = 5
x += 3 # Equivalent to x = x + 3
print(x) # Output: 8
article enumitem
Python Strings and Lists Your Name October 29, 2023
14 Strings
In Python, a string is a sequence of characters enclosed within either single (’ ’)
or double (” ”) quotes. Strings are immutable, meaning their contents cannot
be changed after creation.
Examples:
# Single-quoted string
single_quoted = ’Hello, World!’
# Double-quoted string
double_quoted = "Python is awesome"
# Escaping characters
escaped_string = "He said, \"Python is fun!\""
15 Functions in Strings
Python provides various built-in functions to manipulate strings, including:
• len(): Returns the length of the string.
• lower(): Converts the string to lowercase.
• upper(): Converts the string to uppercase.
5
• strip(): Removes leading and trailing whitespace.
• replace(): Replaces a substring with another.
Examples:
text = " Python Programming "
print(len(text)) # Output: 24
INSIDEAIML
print(text.lower()) # Output: " python programming "
print(text.strip()) # Output: "Python Programming"
print(text.replace("P", "Java")) # Output: " Javaython Javarogramming "
16 Multiline Strings
To create multiline strings, you can use triple single (”’ ”’) or double (””” ”””)
quotes. Multiline strings are often used for docstrings and preserving formatting.
Examples:
multiline_str = ’’’
This is a multiline string.
It can span multiple lines.
’’’
print(multiline_str)
html_code = """
<html>
<head>
<title>My Page</title>
</head>
<body>
<h1>Welcome to my website</h1>
</body>
</html>
"""
print(html_code)
17 Indexing
String characters can be accessed using indexing, where the first character is at
index 0, the second at index 1, and so on. Negative indices count from the end
of the string (-1 for the last character).
Examples:
text = "Python"
print(text[0]) # Output: "P"
print(text[-1]) # Output: "n"
print(text[2]) # Output: "t"
6
18 Slicing
Slicing allows you to extract a portion of a string. It is done by specifying a
start and end index (exclusive). Slicing can also include a step size.
Examples:
text = "Python Programming"
print(text[7:11]) # Output: "Prog"
INSIDEAIML
print(text[:6])
print(text[12:])
print(text[::2])
# Output:
# Output:
# Output:
"Python"
"ming"
"Pto rgamn"
19 List
A list is a collection of items that can be of different data types. Lists are
ordered and mutable, meaning you can change their contents.
Examples:
my_list = [1, 2, 3, 4, 5]
fruits = ["apple", "banana", "cherry"]
mixed_list = [1, "apple", True, 3.14]
# Accessing elements
print(my_list[2]) # Output: 3
print(fruits[-1]) # Output: "cherry"
# Modifying elements
fruits[1] = "orange"
print(fruits) # Output: ["apple", "orange", "cherry"]
# List concatenation
combined_list = my_list + fruits
print(combined_list) # Output: [1, 2, 3, 4, 5, "apple", "orange", "cherry"]
article enumitem
Python Data Structures Your Name October 29, 2023
20 Functions in List
Python provides various built-in functions to manipulate lists, including:
• append(): Adds an element to the end of the list.
7
• pop(): Removes and returns an element by index.
• sort(): Sorts the list in ascending order.
Examples:
my_list = [1, 2, 3, 4, 5]
my_list.append(6)
INSIDEAIML
my_list.insert(2, 7)
my_list.remove(3)
element = my_list.pop(4)
my_list.sort()
21 Tuple
A tuple is an ordered collection of elements, similar to a list. However, tuples
are immutable, meaning their contents cannot be changed after creation.
Examples:
my_tuple = (1, 2, 3, 4, 5)
coordinates = (3.14, 2.71)
mixed_tuple = (1, "apple", True)
# Accessing elements
print(my_tuple[2]) # Output: 3
print(coordinates[-1]) # Output: 2.71
22 Functions in Tuple
Tuples have limited methods due to their immutability. Some common opera-
tions include:
print(count_2) # Output: 3
print(index_3) # Output: 3
8
23 Set
A set is an unordered collection of unique elements. Sets are defined using curly
braces {} or the set() constructor.
Examples:
my_set = {1, 2, 3, 4, 5}
fruits = set(["apple", "banana", "cherry"])
INSIDEAIML
mixed_set = set([1, "apple", True, 3.14])
24 Functions in Set
Sets have various built-in methods for set operations, such as:
• union(): Returns the union of two sets.
• intersection(): Returns the intersection of two sets.
• difference(): Returns the difference between two sets.
set1 = {1, 2, 3, 4, 5}
set2 = {4, 5, 6, 7}
union_set = set1.union(set2)
intersection_set = set1.intersection(set2)
difference_set = set1.difference(set2)
is_subset = set1.issubset(set2)
9
25 Dictionary
A dictionary is an unordered collection of key-value pairs. Keys are unique, and
they are used to access values.
Examples:
my_dict = {"name": "Alice", "age": 30, "city": "New York"}
student = dict(name="Bob", age=25, grade="A")
INSIDEAIML
empty_dict = {}
# Accessing elements
print(my_dict["name"]) # Output: "Alice"
print(student["grade"]) # Output: "A"
article enumitem
Python Basics and Operators Your Name October 29, 2023
26 List Slicing
List slicing allows you to extract a portion of a list. It is done by specifying a
start and end index (exclusive). Slicing can also include a step size.
Examples:
my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
27 Conditional Statements
Conditional statements allow you to make decisions in your code using if, elif
(else if), and else blocks.
Examples:
x = 10
if x > 0:
print("x is positive")
elif x < 0:
print("x is negative")
10
else:
print("x is zero")
28 Comparison Operators
Comparison operators are used to compare values. They include:
INSIDEAIML
• ==: Equal to
• !=: Not equal to
• <: Less than
Examples:
a = 5
b = 7
29 Mathematical Operators
Mathematical operators allow you to perform arithmetic operations on numbers.
They include +, -, *, /, and % (modulo).
Examples:
x = 10
y = 3
sum_result = x + y # Output: 13
difference = x - y # Output: 7
product = x * y # Output: 30
quotient = x / y # Output: 3.3333333333333335
remainder = x % y # Output: 1
11
30 Logical Operators
Logical operators are used to combine and manipulate Boolean values. They
include and, or, and not.
Examples:
x = True
y = False
INSIDEAIML
result1 = x and y
result2 = x or y
result3 = not x
# Output: False
# Output: True
# Output: False
article enumitem
Python Loops and Exception Handling Your Name October 29, 2023
31 For Loops
A for loop is used for iterating over a sequence (list, tuple, string, etc.) or
other iterable objects. It executes a block of code repeatedly until the iterable
is exhausted.
Examples:
# Example 1: Loop through a list
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
12
32 While Loops
A while loop is used for repeatedly executing a block of code as long as a
condition is true.
Examples:
# Example 1: Basic while loop
count = 0
INSIDEAIML
while count < 5:
print(count)
count += 1
33 Advantages of Loops
Advantages of using loops include:
• Automation of repetitive tasks.
13
• Efficient processing of large amounts of data.
• Improved code readability by reducing redundancy.
• Handling dynamic data structures.
• Simplifying complex logic.
34
INSIDEAIML
break and continue
- break is used to exit the loop prematurely when a certain condition is met. -
continue is used to skip the current iteration and proceed to the next one.
Examples:
# Example 1: Using break
for i in range(10):
if i == 5:
break
print(i)
35 range()
The range() function generates a sequence of numbers that can be used in
loops.
Examples:
# Example 1: range with one argument (stop)
for i in range(5):
print(i)
14
36 for-else Statement
A for-else statement is used to execute a block of code in the else part when
the loop completes without encountering a break statement.
Examples:
# Example 1: Using for-else
fruits = ["apple", "banana", "cherry"]
INSIDEAIML
for fruit in fruits:
if fruit == "orange":
else:
break
37 Exceptions
Exceptions are runtime errors that can be handled in Python using try, except,
finally blocks.
Examples:
# Example 1: Handling a division by zero error
try:
result = 10 / 0
except ZeroDivisionError:
print("Division by zero error!")
15
print("Finally block executed.")
article enumitem
Python Functions Your Name October 29, 2023
38 Functions
INSIDEAIML
A function is a reusable block of code that performs a specific task. Functions
help in modularizing code and making it more organized.
Examples:
# Example 1: A simple function
def greet():
print("Hello, World!")
39 Creating Functions
Functions are defined using the def keyword, followed by the function name
and a set of parentheses containing optional parameters.
16
Examples:
# Example 1: Function without parameters
def greet():
print("Hello, World!")
INSIDEAIML
return a + b
40 Calling Functions
Functions are called or invoked by using their name followed by parentheses.
Arguments can be passed inside the parentheses.
Examples:
# Example 1: Calling a function without parameters
greet()
17
def power(base, exponent=2):
return base ** exponent
42
INSIDEAIML
result = power(2, 3)
Keyword Arguments
Keyword arguments allow you to specify arguments by their parameter names
when calling a function. This can make function calls more readable and flexible.
Examples:
# Example 1: Function with two parameters
def greet(name, message):
print(f"Hello, {name}! {message}")
43 Default Arguments
Default arguments are values assigned to parameters in a function’s definition.
If no argument is provided for that parameter when calling the function, the
default value is used.
Examples:
18
greet() # Output: "Hello, Guest!"
INSIDEAIML
print(f"Name: {name}, Age: {age}, City: {city}")
44 Class
A class is a blueprint for creating objects. It defines a set of attributes and
methods that an object of that class will have.
Examples:
def area(self):
return 3.14159 * self.radius ** 2
19
class Car:
brand = "Toyota"
model = "Camry"
45 Objects
Objects are instances of classes. They are created based on the blueprint defined
INSIDEAIML
by the class and can have their own unique attribute values.
Examples:
# Example 1: Creating objects from a class
dog1 = Dog()
dog2 = Dog()
46 Define a Class
To define a class in Python, use the class keyword followed by the class name
and a colon. You can include attributes and methods within the class definition.
Examples:
# Example 1: A simple class definition
class Dog:
pass
20
age = 0
def area(self):
INSIDEAIML
return 3.14159 * self.radius ** 2
def area(self):
return 3.14159 * self.radius ** 2
21
length = 0
width = 0
def area(self):
return self.length * self.width
INSIDEAIML
class Car:
brand = "Toyota"
model = "Camry"
22
49 Self Keyword
The self keyword refers to the current instance of the class and is used to
access and modify class attributes within methods.
Examples:
# Example 1: Using self to access attributes
class Person:
INSIDEAIML
name = ""
def display_name(self):
return self.name
50 init ()
The init () method is a special method in Python classes that is automat-
ically called when an object is created from the class. It is used to initialize
attributes.
Examples:
# Example 1: Class with constructor (__init__)
class Student:
def __init__(self, name, age):
self.name = name
self.age = age
circle1 = Circle()
circle2 = Circle(5)
23
51 pass Statement
The pass statement is a placeholder that does nothing. It is often used when a
statement is syntactically required but no action is needed.
Examples:
# Example 1: Using pass in a class definition
class EmptyClass:
pass
INSIDEAIML
# Example 2: Using pass in a function or method definition
def empty_function():
pass
class MyClass:
def my_method(self):
pass
52 Inheritance
Inheritance is a mechanism in Python that allows you to create a new class by
inheriting attributes and methods from an existing class.
Examples:
# Example 1: Base class (Parent class)
class Animal:
def speak(self):
pass
def area(self):
return self.length * self.width
24
class Square(Rectangle):
def __init__(self, side_length):
super().__init__(side_length, side_length)
class B:
INSIDEAIML
def method_A(self):
pass
def method_B(self):
pass
class Child(Parent):
def display(self):
print("Child class")
child_obj = Child()
child_obj.display() # Output: "Child class"
article enumitem
Python Abstraction, Polymorphism, and NumPy Your Name October 29,
2023
53 Abstraction
Abstraction is a fundamental concept in programming that involves hiding the
complex implementation details and showing only the necessary features of an
object.
Examples:
class Circle(Shape):
25
def area(self):
return 3.14159 * self.radius ** 2
INSIDEAIML
# Example 3: Abstraction in a library
import math
radius = 5
circle_area = math.pi * radius ** 2
54 Abstract Class
An abstract class is a class that cannot be instantiated and is meant to be
subclassed. It may contain abstract methods that must be implemented by its
subclasses.
Examples:
# Example 1: Defining an abstract class
from abc import ABC, abstractmethod
class Shape(ABC):
@abstractmethod
def area(self):
pass
def area(self):
return 3.14159 * self.radius ** 2
26
55 Abstract Method
An abstract method is a method declared in an abstract class that must be
implemented by any concrete (non-abstract) subclass.
Examples:
# Example 1: Defining an abstract class
from abc import ABC, abstractmethod
INSIDEAIML
class Shape(ABC):
@abstractmethod
def area(self):
pass
def area(self):
return 3.14159 * self.radius ** 2
56 Polymorphism
Polymorphism is the ability of different objects to respond to the same method
or function in different ways. It allows objects of different classes to be treated
as objects of a common base class.
Examples:
# Example 1: Polymorphism with a base class
class Animal:
def speak(self):
pass
class Dog(Animal):
def speak(self):
return "Woof!"
class Cat(Animal):
def speak(self):
return "Meow!"
27
# Example 2: Polymorphism with a common interface
def animal_speak(animal):
return animal.speak()
dog = Dog()
cat = Cat()
INSIDEAIML
# Example 3: Polymorphism with functions
def add(a, b):
return a + b
result1 = add(5, 3)
result2 = add("Hello, ", "World!")
calc = Calculator()
result3 = calc.add(2, 3, 4)
vector1 = Vector(1, 2)
vector2 = Vector(3, 4)
result4 = vector1 + vector2
28
# Example 2: Creating a 1D NumPy array
arr1 = np.array([1, 2, 3, 4, 5])
INSIDEAIML
# Example 4: Creating a 3D NumPy array
arr3 = np.array([[[1, 2], [3, 4]], [[5, 6], [7, 8]]])
29
# Example 2: Checking the dimension of a 2D NumPy array
arr2 = np.array([[1, 2, 3], [4, 5, 6]])
dim2 = arr2.ndim # Output: 2
INSIDEAIML
# Example 4: Checking the dimension of a 1D array using shape
arr4 = np.arange(1, 6)
dim4 = arr4.shape # Output: (5,)
30
Examples:
# Example 1: Splitting a 1D NumPy array using split
arr1 = np.array([1, 2, 3, 4, 5, 6])
split_arr1 = np.split(arr1, 3) # Splits into 3 equal parts
INSIDEAIML
split_arr2 = np.hsplit(arr2, 3) # Splits horizontally into 3 equal parts
31
split_arr3 = np.vsplit(arr3, 3)
INSIDEAIML
arr4 = np.array([1, 2, 3, 4, 5, 6])
split_arr4 = np.split(arr4, [2, 4])
63 Pandas
Pandas is a popular Python library for data manipulation and analysis. It
provides data structures like DataFrame for handling tabular data efficiently.
Examples:
# Example 1: Importing pandas
import pandas as pd
32
# Example 5: Changing the index of a DataFrame
df.set_index(’Name’, inplace=True)
INSIDEAIML
and integer location, respectively.
Examples:
# Example 1: Accessing data using loc (label-based)
data = {’Name’: [’Alice’, ’Bob’, ’Charlie’],
’Age’: [25, 30, 35]}
df = pd.DataFrame(data)
33
’Age’: [25, 30, 35]}
df = pd.DataFrame(data)
34
70 Check the Number of Rows and Columns
You can use the shape attribute to check the number of rows and columns
in a DataFrame.
Examples:
# Example 1: Checking the number of rows and columns
num_rows, num_columns = df.shape
71 INSIDEAIML
Clean the Null Values - Numeric Values
You can use the fillna() method to clean null values in a DataFrame,
particularly for numeric values.
Examples:
# Example 1: Cleaning null values in a numeric column
df[’Age’].fillna(0, inplace=True) # Fill null values in ’Age’ with 0
74 Matplotlib
Matplotlib is a popular Python library for creating static, animated, and inter-
active visualizations.
Examples:
35
# Example 1: Importing matplotlib
import matplotlib.pyplot as plt
INSIDEAIML
# Example 3: Creating a bar chart
categories = [’A’, ’B’, ’C’, ’D’]
values = [10, 30, 20, 15]
plt.bar(categories, values)
36
y = [10, 20, 25, 30, 35]
plt.scatter(x, y)
INSIDEAIML
37