0% found this document useful (0 votes)
15 views

Python Notes

Python notes by AJAY

Uploaded by

John Rai
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views

Python Notes

Python notes by AJAY

Uploaded by

John Rai
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 37

Programming and Scientific Computing Notes

InsideAIML

INSIDEAIML October 29, 2023

1 What is a Programming Language and Why


Do We Need It?
A programming language is a formal means of communicating instructions to
a computer. It consists of a set of rules and syntax that allow programmers to
write code that can be executed by a computer. Programming languages serve
several purposes:

• Communication: They allow programmers to communicate their inten-


tions and instructions to a computer effectively.
• Automation: Programming languages enable automation of tasks, mak-
ing it possible to perform complex and repetitive tasks quickly and accu-
rately.
• Problem Solving: They provide a means to express solutions to various
problems, from simple calculations to complex algorithms.
• Software Development: Programming languages are essential for de-
veloping software applications, ranging from simple scripts to large-scale
applications.

• Control: They provide control over hardware and software resources,


allowing developers to manipulate data and perform operations.

2 Compiler and Interpreter in Python


In Python, we encounter both compilation and interpretation:

• Compiler: Python uses a compiler to convert its source code into byte-
code. This bytecode is a lower-level representation of the code.

• Interpreter: After compilation, Python uses an interpreter (Python Vir-


tual Machine or PVM) to execute the bytecode. It processes the code line
by line.

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.

4 Installing Anaconda and Jupyter


To set up Anaconda and Jupyter:

1. Anaconda: Download and install Anaconda from the official website


(https://www.anaconda.com/).
2. Jupyter: After installing Anaconda, you can install Jupyter by running
the following command in your terminal or command prompt:

conda install -c anaconda jupyter

To start a Jupyter notebook, use the following command:

jupyter notebook

5 Comments, Writing and Executing Code in


Python
In Python:

• Comments: Use ‘‘ to create comments. They are for documentation and


are not executed by the interpreter.
• Writing and Executing Code: Python code can be written in a text
editor or a Jupyter notebook. To execute code in a Jupyter notebook,
run the cell containing the code. In a script, use the ‘python‘ command
followed by the script’s filename.

6 Variables, Memory, and Space Management


In Python:

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

7 Input from User


In Python, you can take input from the user using the input() function. It
reads a line of text from the user as a string.
Example:
name = input("Enter your name: ")
print("Hello, " + name)

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:

13.1 Input and Output


name = input("Enter your name: ")
print(f"Hello, {name}!")

13.2 Formatted String


name = "Alice"
age = 30
print(f"My name is {name} and I am {age} years old.")

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.

• insert(): Inserts an element at a specified position.


• remove(): Removes the first occurrence of an element.

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()

print(my_list) # Output: [1, 2, 4, 6, 7]


print(element) # Output: 5

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:

• count(): Counts the number of occurrences of a value.


• index(): Returns the index of the first occurrence of a value.
Examples:
my_tuple = (1, 2, 2, 3, 4, 2)
count_2 = my_tuple.count(2)
index_3 = my_tuple.index(3)

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])

# Adding and removing elements


my_set.add(6)
fruits.remove("banana")

print(my_set) # Output: {1, 2, 3, 4, 5, 6}


print(fruits) # Output: {"apple", "cherry"}

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.

• issubset(): Checks if one set is a subset of another.


• add(): Adds an element to the set.
Examples:

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)

print(union_set) # Output: {1, 2, 3, 4, 5, 6, 7}


print(intersection_set) # Output: {4, 5}
print(difference_set) # Output: {1, 2, 3}
print(is_subset) # Output: False

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]

# Extract elements from index 2 to 5 (exclusive)


slice1 = my_list[2:5] # Output: [3, 4, 5]

# Slice with step size 2


slice2 = my_list[1:8:2] # Output: [2, 4, 6, 8]

# Reverse the list


reverse_slice = my_list[::-1] # Output: [10, 9, 8, 7, 6, 5, 4, 3, 2, 1]

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

• >: Greater than


• <=: Less than or equal to
• >=: Greater than or equal to

Examples:
a = 5
b = 7

print(a == b) # Output: False


print(a != b) # Output: True
print(a < b) # Output: True
print(a > b) # Output: False

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)

# Example 2: Loop through a string


for letter in "Python":
print(letter)

# Example 3: Loop using range()


for i in range(5):
print(i)

# Example 4: Loop with custom step


for i in range(1, 10, 2):
print(i)

# Example 5: Loop through a dictionary


student_scores = {"Alice": 85, "Bob": 92, "Charlie": 78}
for name, score in student_scores.items():
print(f"{name}: {score}")

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

# Example 2: Loop with break statement


num = 1
while num <= 10:
if num == 5:
break
print(num)
num += 1

# Example 3: Loop with continue statement


num = 0
while num < 5:
num += 1
if num == 3:
continue
print(num)

# Example 4: Loop with else block


count = 0
while count < 5:
print(count)
count += 1
else:
print("Loop completed!")

# Example 5: Infinite loop (use with caution)


while True:
print("This is an infinite loop")
break

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)

# Example 2: Using continue


for i in range(6):
if i == 3:
continue
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)

# Example 2: range with two arguments (start, stop)


for i in range(2, 7):
print(i)

# Example 3: range with three arguments (start, stop, step)


for i in range(1, 10, 2):
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

print("No oranges found!")

# Example 2: Loop without a break


numbers = [1, 2, 3, 4, 5]
for num in numbers:
if num > 10:
break
else:
print("No numbers greater than 10 found!")

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!")

# Example 2: Handling a value error


try:
value = int("abc")
except ValueError as e:
print(f"Value error: {e}")

# Example 3: Using the finally block


try:
x = 5 / 0
except ZeroDivisionError:
print("Division by zero error!")
finally:

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!")

# Example 2: Function with parameters


def add(a, b):
return a + b

# Example 3: Function with a docstring


def square(x):
"""
This function returns the square of a number.
"""
return x * x

# Example 4: Function with a return statement


def is_even(num):
if num % 2 == 0:
return True
else:
return False

# Example 5: Function with multiple return statements


def get_grade(score):
if score >= 90:
return "A"
elif score >= 80:
return "B"
else:
return "C"

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!")

# Example 2: Function with parameters


def add(a, b):

INSIDEAIML
return a + b

# Example 3: Function with a docstring


def square(x):
"""
This function returns the square of a number.
"""
return x * x

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()

# Example 2: Calling a function with arguments


result = add(5, 3)

# Example 3: Calling a function with a single argument


value = square(4)

41 Parameters and Arguments


Parameters are variables defined in the function’s definition. Arguments are
values passed to the function when it is called.
Examples:
# Example 1: Function with two parameters
def add(a, b):
return a + b

# Example 2: Calling the function with arguments


result = add(5, 3)

# Example 3: Function with default parameters

17
def power(base, exponent=2):
return base ** exponent

# Example 4: Calling the function with one argument


result = power(3)

# Example 5: Calling the function with two arguments

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}")

# Example 2: Calling the function with keyword arguments


greet(name="Alice", message="How are you?")

# Example 3: Mixing positional and keyword arguments


greet("Bob", message="Nice to meet you!")

# Example 4: Function with default keyword argument


def repeat(text, times=2):
print(text * times)

# Example 5: Using keyword argument for a default parameter


repeat("Hello") # Output: "HelloHello"
repeat("Python", times=3) # Output: "PythonPythonPython"

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:

# Example 1: Function with a default parameter


def greet(name="Guest"):
print(f"Hello, {name}!")

# Example 2: Calling the function without an argument

18
greet() # Output: "Hello, Guest!"

# Example 3: Calling the function with an argument


greet("Alice") # Output: "Hello, Alice!"

# Example 4: Function with multiple default parameters


def get_info(name, age=30, city="New York"):

INSIDEAIML
print(f"Name: {name}, Age: {age}, City: {city}")

# Example 5: Calling the function


get_info("Bob")
with various arguments
# Output: "Name: Bob, Age: 30, City: New York"
get_info("Charlie", 25) # Output: "Name: Charlie, Age: 25, City: New York"
get_info("David", 40, "Chicago") # Output: "Name: David, Age: 40, City: Chicago"
article enumitem
Python Classes and Inheritance Your Name October 29, 2023

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:

# Example 1: A simple class definition


class Dog:
pass

# Example 2: Class with attributes


class Person:
name = ""
age = 0

# Example 3: Class with methods


class Circle:
radius = 0

def area(self):
return 3.14159 * self.radius ** 2

# Example 4: Class with constructor (__init__)


class Student:
def __init__(self, name, age):
self.name = name
self.age = age

# Example 5: Class with class-level attributes

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()

# Example 2: Creating objects with attribute values


person1 = Person()
person1.name = "Alice"
person1.age = 30

# Example 3: Creating objects and using methods


circle = Circle()
circle.radius = 5
area = circle.area()

# Example 4: Creating objects with constructor


student1 = Student("Bob", 25)

# Example 5: Accessing class-level attributes


car1 = Car()
car2 = Car()
car2.model = "Corolla"

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

# Example 2: Class with attributes


class Person:
name = ""

20
age = 0

# Example 3: Class with methods


class Circle:
radius = 0

def area(self):

INSIDEAIML
return 3.14159 * self.radius ** 2

# Example 4: Class with constructor (__init__)


class Student:
def __init__(self, name, age):
self.name = name
self.age = age

# Example 5: Class with class-level attributes


class Car:
brand = "Toyota"
model = "Camry"

47 Attributes and Methods


Attributes are variables that store data within a class. Methods are functions
defined inside a class that perform actions related to the class.
Examples:
# Example 1: Class with attributes
class Person:
name = ""
age = 0

# Example 2: Class with methods


class Circle:
radius = 0

def area(self):
return 3.14159 * self.radius ** 2

# Example 3: Class with constructor (__init__)


class Student:
def __init__(self, name, age):
self.name = name
self.age = age

# Example 4: Class with methods


class Rectangle:

21
length = 0
width = 0

def area(self):
return self.length * self.width

# Example 5: Class with class-level attributes

INSIDEAIML
class Car:
brand = "Toyota"
model = "Camry"

48 Access the Attributes and Methods of a Class


through Objects
You can access attributes and methods of a class through objects using the dot
notation.
Examples:
# Example 1: Accessing attributes of an object
person1 = Person()
person1.name = "Alice"
person1.age = 30
name = person1.name

# Example 2: Accessing methods of an object


circle = Circle()
circle.radius = 5
area = circle.area()

# Example 3: Accessing attributes using constructor


student1 = Student("Bob", 25)
student_name = student1.name

# Example 4: Accessing methods of an object


rectangle = Rectangle()
rectangle.length = 4
rectangle.width = 3
area = rectangle.area()

# Example 5: Accessing class-level attributes


car1 = Car()
brand = car1.brand
model = car1.model

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

# Example 2: Using self to modify attributes


class Rectangle:
length = 0
width = 0

def set_dimensions(self, length, width):


self.length = length
self.width = width

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

student1 = Student("Bob", 25)


name = student1.name

# Example 2: Using __init__ to set default values


class Circle:
def __init__(self, radius=0):
self.radius = radius

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

# Example 3: Using pass in a conditional statement


if True:
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

# Example 2: Derived class (Child class)


class Dog(Animal):
def speak(self):
return "Woof!"

# Example 3: Inheriting attributes and methods


class Rectangle:
def __init__(self, length, width):
self.length = length
self.width = width

def area(self):
return self.length * self.width

24
class Square(Rectangle):
def __init__(self, side_length):
super().__init__(side_length, side_length)

# Example 4: Multiple inheritance


class A:

class B:
INSIDEAIML
def method_A(self):
pass

def method_B(self):
pass

class C(A, B):


pass

# Example 5: Method overriding


class Parent:
def display(self):
print("Parent class")

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:

# Example 1: Abstraction using a class


class Shape:
def area(self):
pass

class Circle(Shape):

25
def area(self):
return 3.14159 * self.radius ** 2

# Example 2: Abstraction with functions


def calculate_area(shape):
return shape.area()

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

# Example 2: Subclassing an abstract class


class Circle(Shape):
def __init__(self, radius):
self.radius = radius

def area(self):
return 3.14159 * self.radius ** 2

# Example 3: Attempting to create an instance of an abstract class


try:
shape = Shape()
except TypeError as e:
print(f"Error: {e}")

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

# Example 2: Implementing an abstract method in a subclass


class Circle(Shape):
def __init__(self, radius):
self.radius = radius

def area(self):
return 3.14159 * self.radius ** 2

# Example 3: Attempting to create a subclass without implementing the abstract method


class Triangle(Shape):
pass

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!")

# Example 4: Polymorphism with method overloading


class Calculator:
def add(self, a, b):
return a + b

def add(self, a, b, c):


return a + b + c

calc = Calculator()
result3 = calc.add(2, 3, 4)

# Example 5: Polymorphism with operator overloading


class Vector:
def __init__(self, x, y):
self.x = x
self.y = y

def __add__(self, other):


return Vector(self.x + other.x, self.y + other.y)

vector1 = Vector(1, 2)
vector2 = Vector(3, 4)
result4 = vector1 + vector2

57 Libraries and Modules (NumPy)


Libraries and modules are collections of pre-written code that can be used to
extend Python’s functionality.
Examples using NumPy:
# Example 1: Importing the NumPy library
import numpy as np

28
# Example 2: Creating a 1D NumPy array
arr1 = np.array([1, 2, 3, 4, 5])

# Example 3: Creating a 2D NumPy array


arr2 = np.array([[1, 2, 3], [4, 5, 6]])

INSIDEAIML
# Example 4: Creating a 3D NumPy array
arr3 = np.array([[[1, 2], [3, 4]], [[5, 6], [7, 8]]])

# Example 5: Checking the dimension of a NumPy array


dim1 = arr1.ndim
dim2 = arr2.ndim
dim3 = arr3.ndim

58 Creation of 1D, 2D, and 3D Array (NumPy)


NumPy allows you to create arrays with one, two, or three dimensions, which
can be used for various data processing tasks.
Examples:
# Example 1: Creating a 1D NumPy array
arr1 = np.array([1, 2, 3, 4, 5])

# Example 2: Creating a 2D NumPy array


arr2 = np.array([[1, 2, 3], [4, 5, 6]])

# Example 3: Creating a 3D NumPy array


arr3 = np.array([[[1, 2], [3, 4]], [[5, 6], [7, 8]]])

# Example 4: Creating a 1D array using arange


arr4 = np.arange(1, 6)

# Example 5: Creating a 2D array using reshape


arr5 = np.arange(1, 7).reshape(2, 3)

59 Checking the Dimension of an Array (NumPy)


You can check the dimensionality of a NumPy array using the ndim attribute.
Examples:
# Example 1: Checking the dimension of a 1D NumPy array
arr1 = np.array([1, 2, 3, 4, 5])
dim1 = arr1.ndim # Output: 1

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

# Example 3: Checking the dimension of a 3D NumPy array


arr3 = np.array([[[1, 2], [3, 4]], [[5, 6], [7, 8]]])
dim3 = arr3.ndim # Output: 3

INSIDEAIML
# Example 4: Checking the dimension of a 1D array using shape
arr4 = np.arange(1, 6)
dim4 = arr4.shape # Output: (5,)

# Example 5: Checking the dimension of a 2D array using shape


arr5 = np.arange(1, 7).reshape(2, 3)
dim5 = arr5.shape # Output: (2, 3)

60 Checking the Datatype of an Array (NumPy)


You can check the datatype of a NumPy array using the dtype attribute.
Examples:
# Example 1: Checking the datatype of a NumPy array
arr1 = np.array([1, 2, 3, 4, 5])
dtype1 = arr1.dtype # Output: int64

# Example 2: Checking the datatype of a NumPy array


arr2 = np.array([1.0, 2.5, 3.7])
dtype2 = arr2.dtype # Output: float64

# Example 3: Checking the datatype of a NumPy array


arr3 = np.array(["apple", "banana", "cherry"])
dtype3 = arr3.dtype # Output: <U6 (Unicode string of 6 characters)

# Example 4: Checking the datatype of a NumPy array


arr4 = np.array([True, False, True])
dtype4 = arr4.dtype # Output: bool

# Example 5: Checking the datatype of a NumPy array


arr5 = np.array([1, 2, 3], dtype=np.float32)
dtype5 = arr5.dtype # Output: float32

61 Splitting the NumPy Array (NumPy)


You can split a NumPy array into multiple smaller arrays using various methods
like split, hsplit, and vsplit.

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

# Example 2: Splitting a 2D NumPy array using hsplit


arr2 = np.array([[1, 2, 3], [4, 5, 6]])

INSIDEAIML
split_arr2 = np.hsplit(arr2, 3) # Splits horizontally into 3 equal parts

# Example 3: Splitting a 2D NumPy array using vsplit


arr3 = np.array([[1, 2], [3, 4], [5, 6]])
split_arr3 = np.vsplit(arr3, 3) # Splits vertically into 3 equal parts

# Example 4: Splitting a 1D NumPy array at specified indices


arr4 = np.array([1, 2, 3, 4, 5, 6])
split_arr4 = np.split(arr4, [2, 4]) # Splits at indices 2 and 4

# Example 5: Splitting a 2D NumPy array at specified column indices


arr5 = np.array([[1, 2, 3], [4, 5, 6]])
split_arr5 = np.hsplit(arr5, [1, 2]) # Splits at columns 1 and 2

62 Access the Splitted Array (NumPy)


After splitting a NumPy array, you can access the individual parts using index-
ing.
Examples:
# Example 1: Accessing parts of a 1D splitted array
arr1 = np.array([1, 2, 3, 4, 5, 6])
split_arr1 = np.split(arr1, 3)

part1 = split_arr1[0] # First part


part2 = split_arr1[1] # Second part
part3 = split_arr1[2] # Third part

# Example 2: Accessing parts of a 2D splitted array


arr2 = np.array([[1, 2, 3], [4, 5, 6]])
split_arr2 = np.hsplit(arr2, 3)

part1 = split_arr2[0] # First part


part2 = split_arr2[1] # Second part
part3 = split_arr2[2] # Third part

# Example 3: Accessing parts of a 2D splitted array


arr3 = np.array([[1, 2], [3, 4], [5, 6]])

31
split_arr3 = np.vsplit(arr3, 3)

part1 = split_arr3[0] # First part


part2 = split_arr3[1] # Second part
part3 = split_arr3[2] # Third part

# Example 4: Accessing specific parts after splitting

INSIDEAIML
arr4 = np.array([1, 2, 3, 4, 5, 6])
split_arr4 = np.split(arr4, [2, 4])

part1 = split_arr4[0] # First part


part2 = split_arr4[1] # Second part
part3 = split_arr4[2] # Third part

# Example 5: Accessing specific parts after splitting


arr5 = np.array([[1, 2, 3], [4, 5, 6]])
split_arr5 = np.hsplit(arr5, [1, 2])

part1 = split_arr5[0] # First part


part2 = split_arr5[1] # Second part
part3 = split_arr5[2] # Third part
article enumitem
Python Pandas and Matplotlib Your Name October 29, 2023

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

# Example 2: Creating a DataFrame from a dictionary


data = {’Name’: [’Alice’, ’Bob’, ’Charlie’],
’Age’: [25, 30, 35]}
df = pd.DataFrame(data)

# Example 3: Accessing data using loc (label-based)


row1 = df.loc[0]
cell1 = df.loc[1, ’Name’]

# Example 4: Accessing data using iloc (integer-based)


row2 = df.iloc[1]
cell2 = df.iloc[2, 1]

32
# Example 5: Changing the index of a DataFrame
df.set_index(’Name’, inplace=True)

64 Locate an Index - loc and iloc


The loc and iloc methods are used to access data in a DataFrame by label

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)

row1 = df.loc[0] # Access the first row


cell1 = df.loc[1, ’Name’] # Access a specific cell by label

# Example 2: Accessing data using iloc (integer-based)


row2 = df.iloc[1] # Access the second row
cell2 = df.iloc[2, 1] # Access a specific cell by integer location

65 Changing the Index


You can change the index of a DataFrame using the seti ndexmethod.
Examples:
# Example 1: Changing the index of a DataFrame
data = {’Name’: [’Alice’, ’Bob’, ’Charlie’],
’Age’: [25, 30, 35]}
df = pd.DataFrame(data)

df.set_index(’Name’, inplace=True) # Change the index to ’Name’

# Example 2: Resetting the index of a DataFrame


df.reset_index(inplace=True) # Reset the index to default integer index

66 Reset the Index


You can reset the index of a DataFrame to the default integer index
using the reseti ndexmethod.
Examples:
# Example 1: Resetting the index of a DataFrame
data = {’Name’: [’Alice’, ’Bob’, ’Charlie’],

33
’Age’: [25, 30, 35]}
df = pd.DataFrame(data)

df.set_index(’Name’, inplace=True) # Change the index to ’Name’


df.reset_index(inplace=True) # Reset the index to default integer index

67 Loading Data from a File (CSV or Excel)


INSIDEAIML
You can load data from external files like CSV or Excel into a DataFrame
using pandas.
Examples:

# Example 1: Loading data from a CSV file


csv_file = ’data.csv’
df_csv = pd.read_csv(csv_file)

# Example 2: Loading data from an Excel file


excel_file = ’data.xlsx’
df_excel = pd.read_excel(excel_file)

68 Getting the Last n Rows, First n Rows


You can use the tail() and head() methods to get the last and first
n rows of a DataFrame.
Examples:
# Example 1: Getting the last 3 rows
last_3_rows = df.tail(3)

# Example 2: Getting the first 2 rows


first_2_rows = df.head(2)

69 Checking the Number of Null Values in Each


Column
You can use the isnull() and sum() functions to check the number of
null values in each column of a DataFrame.
Examples:
# Example 1: Checking null values in each column
null_values = df.isnull().sum()

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

72 Clean the Null Values - Non-Numeric Values


You can use the fillna() method to clean null values in a DataFrame
for non-numeric values.
Examples:
# Example 1: Cleaning null values in a non-numeric column
df[’Name’].fillna(’Unknown’, inplace=True) # Fill null values in ’Name’ with ’Unknown’

73 Saving the DataFrame to the Local System


You can save a DataFrame to a CSV or Excel file using the toc sv()andtoe xcel()methods.Examples:
# Example 1: Saving a DataFrame to a CSV file
df.to_csv(’data.csv’, index=False)

# Example 2: Saving a DataFrame to an Excel file


df.to_excel(’data.xlsx’, index=False)

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

# Example 2: Creating a basic plot


x = [1, 2, 3, 4, 5]
y = [10, 20, 25, 30, 35]
plt.plot(x, y)

INSIDEAIML
# Example 3: Creating a bar chart
categories = [’A’, ’B’, ’C’, ’D’]
values = [10, 30, 20, 15]
plt.bar(categories, values)

# Example 4: Creating a pie chart


labels = [’Apples’, ’Bananas’, ’Cherries’, ’Dates’]
sizes = [30, 45, 15, 10]
plt.pie(sizes, labels=labels, autopct=’%1.1f%%’)

# Example 5: Creating a scatter plot


x = [1, 2, 3, 4, 5]
y = [10, 20, 25, 30, 35]
plt.scatter(x, y)

75 Plotting the Data


Matplotlib provides various functions to create different types of plots, including
bar charts, column charts, pie charts, and scatterplots.
Examples:
# Example 1: Creating a bar chart
categories = [’A’, ’B’, ’C’, ’D’]
values = [10, 30, 20, 15]
plt.bar(categories, values)

# Example 2: Creating a column chart


x = [’Jan’, ’Feb’, ’Mar’, ’Apr’, ’May’]
y = [100, 150, 120, 140, 160]
plt.barh(x, y)

# Example 3: Creating a pie chart


labels = [’Apples’, ’Bananas’, ’Cherries’, ’Dates’]
sizes = [30, 45, 15, 10]
plt.pie(sizes, labels=labels, autopct=’%1.1f%%’)

# Example 4: Creating a scatter plot


x = [1, 2, 3, 4, 5]

36
y = [10, 20, 25, 30, 35]
plt.scatter(x, y)

# Example 5: Creating a line plot


x = [1, 2, 3, 4, 5]
y = [10, 20, 25, 30, 35]
plt.plot(x, y)

INSIDEAIML

37

You might also like