Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
72 views

Python Django Internship Report 5 - Pagenumber

Uploaded by

www.tharunchundi
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
72 views

Python Django Internship Report 5 - Pagenumber

Uploaded by

www.tharunchundi
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 52

PYTHON DJANGO

An Internship report submitted to


Jawaharlal Nehru Technological University, Kakinada,
In the partial fulfillment for the award of the Degree in

BACHELOR OF TECHNOLOGY
IN
COMPUTER SCIENCE & ENGINEERING
Submitted by

BADINENI SIVASAIKRISHNA

21F91A0593

Under the Supervision of

Mr. N.MADHAVARAO M.Tech

PRAKASAM ENGINEERING COLLEGE


(An ISO 9001-2008 & NAAC Accredited Institution)

(Affiliated to Jawaharlal Nehru Technological University, Kakinada)

O.V.ROAD, KANDUKUR-523105, A.P.

A.Y : 2024-2025

1
PRAKASAM ENGINEERING COLLEGE
(An ISO 9001-2008 & NAAC Accredited Institution)

(Affiliated to Jawaharlal Nehru Technological University, Kakinada)

O.V.ROAD, KANDUKUR-523105, A.P.

DEPARTMENTOF
COMPTER SCIENCE & ENGINEERING
BONAFIDE CERTIFICATE
This is to certify that the Internship report entitled “ PYTHON DJANGO” is a bonafide

work of BADINENI SIVASAIKRISHNA(21F91A0593) in the partial fulfillment of the

requirement for the award of the degree in Bachelor of Technology in COMPUTER

SCIENCE & ENGINEERING for the academic year 2024-2025.

Signature of the Coordinator Signature of the HOD

Mr.N.MADHAVARAO M.Tech Mr. M. M. RAYUDU M.Tech, (Ph.D)

Signature of External Examiner

2
3
ACKNOWLEDGEMENT

I feel to render my thankful acknowledgement to the following distinguished personalities,


who stretched their helping hand to me, in completing my mini project work.

I am very grateful and my sincere thanks to our secretary & correspondent


Dr.K.RAMAIAH of PRAKASAM ENGINEERING COLLEGE for giving this
opportunity.

I hereby, express my regards and extend my gratitude to our PRINCIPAL, Dr.CH. RAVI
KUMAR , for giving this opportunity to do the thesis as a part of our course.

I express my deep sense of gratitude to Mr.M.M.RAYUDU, M.Tech(Ph.d), Head of the


Department, Department of CSE for having shown keen interest at every stage of
development of our thesis and guiding us in every aspect.

I am thankful to my Internship Coordinator Mr.N.MADHAVARAO M.Tech who has


channeled my thoughts and timely suggestions.

I would like to thank Mr.RAM TAVVA ExcelR Pvt Ltd , HYDERABAD for giving me the
opportunity to do an internship within the organization.

I would also like to thank all my Faculties in Prakasam Engineering College for their
constant encouragement and for being a great group of knowledgeable and cooperative
people to work with.

BADINENI SIVASAIKRISHNA
21F91A0593

4
INDEX
Introduction To Python

1. Who Discovered Python


2. What Is Python
3. Features Of Python
4. Installation

Introduction To Python Datatypes

1. Variables
2. Keywords
3. Datatypes

Numeric Datatypes

1. Declaration Of Numeric Datatypes


2. Methods Of Numeric Datatypes

Numeric Datatypes(Contd) ,String Lists

1. Declaration Of Strings
2. Methods Of Strings

Lists

1. Declaration Of Lists Datatypes


2. Methods Of List Datatypes

Conditions

1. If Conditions
2. If Else Conditions
3. Elif Conditons
4. Nested If

Control Statements

1. For Loop
2. While Loop
3. Break And Continue
4. Pass Statements

5
Funtions

1. Functions Argumets
2. Variables Scope
3. Global Keywords
4. Recursion
5. Modules
6. Packages
7. Main Function

Files

1. Directory And Files Management


2. Cvs: Read And Write Csv Files
3. Reading Csv Files In Python
4. Writing Csv Files In Python

Exception Handling

1. Exceptions
2. Exception Handing
3. Custom Exceptions

Classes & Objects

1. Object And Class


2. Objects And Classes
3. Inheritance
4. Multiple Inheritance
5. Polymorphism In Python
6. Python Operator Overloading

6
Introduction To Python
Python is a high-level, versatile programming language known for its simplicity, readability,
and wide range of applications. Developed by Guido van Rossum and first released in 1991,
Python's design philosophy emphasizes code readability, using clear and straightforward
syntax that allows programmers to express concepts in fewer lines of code compared to other
languages like Java or C++. Its simple, English-like commands make it an excellent choice for
beginners, while its powerful capabilities have made it a favorite among experienced
developers.

Some key features that make Python popular are:

1. Interpreted Language: Python executes code line by line, which simplifies


debuggingand allows for rapid prototyping.
2. Cross-Platform: Python runs on multiple platforms (Windows, macOS, Linux),
makingit highly portable.
3. Extensive Libraries and Frameworks: Python boasts a vast standard library and
many third-party packages, including popular libraries like NumPy, Pandas,
TensorFlow, Django, and Flask, which support applications in web development,
data science, machine learning, and more.
4. Object-Oriented and Functional Programming: Python supports both object-
oriented and functional programming paradigms, offering flexibility in how
developers structure code.

Python is widely used across fields like web development, scientific computing, artificial
intelligence, data analysis, automation, and more. Its versatility, community support, and vast
ecosystem make it a powerful tool for developers across various industries.

Who Discovered The Python


Python was created by Guido van Rossum, a Dutch programmer, in the late 1980s, and the
first official release was in 1991. Van Rossum began developing Python as a successor to the
ABC programming language, with a focus on creating a language that emphasized code
readability and simplicity. He was inspired by languages like C, Perl, and Lisp but wanted to
build something that was easier to understand and use.

The name "Python" was chosen not after the snake but as a tribute to the British comedy show
Monty Python's Flying Circus, which Van Rossum enjoyed. This whimsical choice reflects
Python's fun and approachable philosophy. Van Rossum continued to guide Python’s
development and was considered its "Benevolent Dictator For Life" (BDFL) until he stepped
down from that role in 2018.

7
What Is Python
Python is a high-level, interpreted programming language that is widely used for a broad
range of applications, from web development and data science to automation and artificial
intelligence. Known for its readable and straightforward syntax, Python enables
programmersto write clear and logical code for both small-scale and large-scale projects.

Key Features of Python:


1. Easy Syntax: Python’s syntax is designed to be easy to read and write, which makes it
ideal for beginners and allows for rapid development.
2. Interpreted Language: Python code is executed line by line, which makes testing and
debugging easy and speeds up development.
3. Multi-Paradigm: Python supports multiple programming paradigms, including
object-oriented, procedural, and functional programming.
4. Extensive Libraries and Frameworks: Python has a vast standard library and a
robustecosystem of third-party libraries, including:
o NumPy and Pandas for data analysis
o TensorFlow and PyTorch for machine learning
o Django and Flask for web development
5. Cross-Platform Compatibility: Python runs on various operating systems, including
Windows, macOS, and Linux, allowing for versatile development.

Common Uses of Python:


 Web Development: Python frameworks like Django and Flask are popular for
buildingweb applications.
 Data Science and Machine Learning: Python is a go-to language for data analysis,
machine learning, and scientific computing, thanks to libraries like NumPy, Pandas,
andTensorFlow.
 Automation/Scripting: Python is often used for scripting repetitive tasks and
automation.
 Game Development: Python can be used for game development, although it’s less
common than C++ or other game-specific languages.
 Internet of Things (IoT): Python, especially with the MicroPython variant, is used in
IoT applications.

Python’s flexibility, extensive community support, and vast libraries make it one of the most
popular programming languages in the world today.

8
Features Of Python
Python has several key features that make it popular among developers for various
applications, from web development and scientific computing to artificial intelligence and
automation. Here are some of its most notable features:

1. Easy-to-Read Syntax
 Python’s syntax is clear and simple, resembling English, which makes it accessible for
beginners and helps experienced developers write clean, readable code.

2. Interpreted Language
 Python is interpreted, meaning the code is executed line by line. This allows for rapid
testing, debugging, and prototyping, as there’s no need to compile the code before
running it.

3. Dynamically Typed
 Python is dynamically typed, meaning you don’t need to declare variable types
explicitly. The type of a variable is determined at runtime, which adds flexibility but
requires careful handling to avoid type errors.

4. Cross-Platform Compatibility
 Python is cross-platform and runs on multiple operating systems, including Windows,
macOS, and Linux, making it highly portable and flexible for various environments.

5. Vast Standard Library and Third-Party Modules


 Python comes with an extensive standard library that includes modules for file
handling, internet protocols, regular expressions, and more. Additionally, there are
numerous third-party libraries, such as:
o NumPy and Pandas for data analysis
o TensorFlow and PyTorch for machine learning
o Flask and Django for web development

6. Object-Oriented and Functional Programming Support


 Python is a multi-paradigm language that supports object-oriented programming
(OOP) for building reusable code and functional programming for writing concise,
functional- style code.

9
7. Automatic Memory Management
 Python handles memory management automatically through garbage collection, which
frees developers from manually managing memory and helps prevent memory leaks.

8. Extensive Community and Support


 Python has one of the largest and most active communities in the programming
world, providing extensive resources, tutorials, and support, as well as continuous
improvementsand libraries for new fields like AI.

9. Embeddable and Extensible


 Python can be embedded into other languages or applications and allows the
integration of C, C++, and Java, making it versatile for enhancing applications with
scripting capabilities.

10. Interactive and Scripting Capabilities


 Python supports interactive mode, allowing developers to test code snippets in real-
time.It’s also widely used for scripting to automate tasks and build tools.

These features make Python a powerful tool for a wide range of applications and industries,
fromsimple scripting to complex machine learning systems.

Installation Of Python
Installing Python on your computer is a straightforward process, and the steps vary slightly
depending on your operating system. Here’s a step-by-step guide:

1. Downloading Python
 Visit the official Python website and go to the Downloads section.
 Select the appropriate version for your operating system (Windows, macOS, or
Linux).It’s usually recommended to download the latest stable release.

2. Installing Python on Windows


 Run the Installer: Double-click the downloaded file to start the installer.

10
 Check “Add Python to PATH”: On the installer screen, check the box that says
“Add Python to PATH.” This is essential for running Python commands from the
command prompt.
 Select “Install Now”: This installs Python with default settings. You can also choose
"Customize installation" if you need to specify the installation location or add
optionalfeatures.
 Complete Installation: Click “Close” once the installation is complete.
 Verify Installation: Open Command Prompt and type:

bash Copy code


python --version

This should display the installed Python version, confirming the installation.

3. Installing Python on macOS


 Use the Installer: Double-click the downloaded .pkg file and follow the prompts to
install Python.
 Verify Installation: Open Terminal and type:

bash Copy code


python3 --version

If the version displays correctly, Python is installed. macOS often comes with Python
2.xpre-installed, so using python3 ensures you’re running the latest version.

4. Installing Python on Linux


 Using Package Managers: Most Linux distributions come with Python pre-installed.
Toinstall or update Python, you can use your package manager. For example:
o Debian/Ubuntu:

bash Copy code


sudo apt update
sudo apt install python3

o Fedora:

bash Copy code


sudo dnf install python3

11
o Arch Linux:

bash Copy code


sudo pacman -S python

 Verify Installation: Open your Terminal and type:

bash Copy code


python3 --version

This should confirm the installation.

5. Installing pip (Python Package Installer)


 pip is usuallyinstalled by default with Python. To check, run:

bash Copy code


pip --version

 If not installed, you can install it manually by following pip installation instructions.

6. Running Python Code

 Open a terminal (Command Prompt on Windows) and simply type python (or
python3
on macOS/Linux) to enter Python’s interactive mode.
 You can also run .py files by typing:

bash Copy code


python filename.py

Once Python is installed, you’re ready to start coding! You can install additional packages
using
pip install package-name as needed for your projects.

Introduction To Python Basic Python Datatypes


In Python, variables, data types, and keywords are essential components of the language that
help structure programs and handle data efficiently. Let’s dive into an introduction of each of
these.

12
1. Variables in Python
A variable is a name that refers to a value stored in memory. Variables are used to store and
manipulate data throughout a program.

Characteristics of Variables in Python:

 Dynamic Typing: You don’t need to declare the type of a variable explicitly. Python infers the
type based on the value assigned.
 Naming Rules:
o Must start with a letter (a-z, A-Z) or an underscore _
o Can contain letters, digits, and underscores (e.g., my_variable, age)
o Cannot use Python keywords as variable names.

Example:
python Copy code
x = 10 # Integername = "Alice" # Stringpi = 3.14 # Float
is_active = True # Boolean

2. Basic Data Types in Python


Data types define the kind of data a variable can hold. Python has several built-in data types
tohandle different types of data, such as numbers, text, and collections.

Core Data Types:

1. Numeric Types:
o Integer (int): Whole numbers, e.g., 42, -7
o Float (float): Numbers with a decimal point, e.g., 3.14, -2.5
o Complex (complex): Numbers with a real and imaginary part, e.g., 1 + 2j
2. String (str): Sequence of characters enclosed in single or double quotes, e.g.,
"Hello,World!".
o Strings are immutable, meaning they cannot be changed after creation.
3. Boolean (bool): Represents truth values, either True or False. Used in conditions and
logical operations.
4. NoneType (None): Represents a null value or no value. The keyword None is used for
this type.
5. Sequences:
o List (list): Ordered, mutable collection of items, e.g., [1, 2, 3]
o Tuple (tuple): Ordered, immutable collection of items, e.g., (1, 2, 3)
o Range (range): Represents a sequence of numbers, typically used in loops, e.g.,
range(5) gives numbers from 0 to 4.
o

13
6. Mappings:
o Dictionary (dict): Unordered collection of key-value pairs, e.g., {"name":
"Alice","age": 25}.
7. Set Types:
o Set (set): Unordered collection of unique items, e.g., {1, 2, 3}
o Frozen Set (frozenset): Similar to a set but immutable.

Each of these data types allows Python to handle different kinds of data effectively.

3. Keywords in Python
Keywords are reserved words in Python that have special meaning and cannot be used as
variable names. Keywords are case-sensitive, and they help define the structure and syntax of
Python code.

Some commonly used Python keywords:

 Control Flow: if, else, elif, for, while


 Logical Operators: and, or, not, in, is
 Functions and Classes: def, class, return, yield
 Data Types: True, False, None
 Error Handling: try, except, finally, raise
 Other: import, from, as, global, nonlocal, pass, break, continue, with

Example:
python Copy code
if True: # `if` and `True` are keywordsprint("Hello")

You can see the full list of Python keywords by using:

python Copy code


import keyword print(keyword.kwlist)

Summary of Variables, Data Types, and Keywords

 Variables: Named storage for data, defined with an assignment, e.g., x = 5.


 Data Types: Define what kind of data can be stored, such as int, float, str, list, dict,
etc.
 Keywords: Reserved words that have special meaning in Python and cannot be used as
identifiers, such as for, while, if, return.

14
Understanding these basic concepts is crucial as they form the foundation of programming in
Python. Each one plays a unique role in helping you manage data and write clear, organized
code.

Numeric Datatypes

1) Declaration of Numeric datatype

2) Methods of Numeric datatype


In Python, numeric data types are used to represent numbers, which can be of several types:
integers, floating-point numbers, and complex numbers. Each of these numeric types has
specificcharacteristics and methods.

1. Declaration of Numeric Data Types


Python supports three primary numeric data types:

 Integer (int): Represents whole numbers without a decimal point. Examples: 42, -7, 0.
 Floating-Point (float): Represents numbers with a decimal point, allowing for fractional
values.Examples: 3.14, -2.5, 0.0.
 Complex (complex): Represents numbers with a real and imaginary part, written as a + bj,
where j is the imaginary unit. Examples: 1 + 2j, -3 + 4j.

Declaring Numeric Types in Python:

To declare a numeric variable, simply assign a number to a variable:

python Copy code# Integer


x = 42 # int

# Float
y = 3.14 # float

# Complex number
z = 2 + 3j # complex

Python automatically assigns the correct data type based on the value.

15
Type Conversion

You can convert between numeric types using int(), float(), and complex() functions:

python Copy code


a = float(5) # Converts integer 5 to 5.0 (float)b = int(3.14) #
Converts float 3.14 to 3 (int)
c = complex(2, 3) # Creates complex number 2 + 3j

2. Methods of Numeric Data Types


Python provides a variety of methods and functions for working with numeric types. Here
aresome of the most commonly used ones:

Common Numeric Methods and Functions

1. abs(): Returns the absolute value of a number.

python Copy code


abs(-7) # Output: 7
abs(-3.14) # Output: 3.14

2. round(): Rounds a floating-point number to a specified number of decimal places.

python Copy code


round(3.14159, 2) # Output: 3.14round(2.71828) # Output: 3

3. pow(): Returns the value of a number raised to a specified power, equivalent to base
**exponent.

python Copy code


pow(2, 3) # Output: 8 (same as 2 ** 3)

4. divmod(): Returns a tuple containing the quotient and remainder when dividing two
numbers.

python Copy code


divmod(10, 3) # Output: (3, 1), where 10 // 3 is 3 and 10 % 3 is 1

16
5. int.bit_length(): Returns the number of bits required to represent an integer in
binary.

python Copy code


(5).bit_length() # Output: 3, since 5 in binary is 101

6. float.is_integer(): Checks if a float has no decimal (whole number).

python Copy code


(5.0).is_integer() # Output: True(5.5).is_integer() # Output:
False

7. complex.real and complex.imag: Access the real and imaginary parts of a complex
number.

python Copy codez = 3 + 4j


z.real # Output: 3.0
z.imag # Output: 4.0

Mathematical Functions (from math module)

The math module in Python provides additional functions specifically for numeric operations,
particularly useful for floating-point calculations:

1. math.sqrt(): Returns the square root of a number.

python Copy code import math


math.sqrt(16) # Output: 4.0

2. math.ceil() and math.floor(): Rounds numbers up or down to the nearest integer.

python Copy code


math.ceil(3.14) # Output: 4math.floor(3.14) # Output: 3

3. math.exp(): Returns the exponential of a number exe^xex.

python Copy code


math.exp(1) # Output: 2.718281828459045 (approximate value of
e)

17
4. math.log(): Returns the natural logarithm (base eee) of a number. Use math.log(x,
base) for custom bases.

python Copy code


math.log(10) # Natural log (ln) of 10
math.log(100, 10) # Logarithm of 100 with base 10, Output: 2

5. math.sin(), math.cos(), math.tan(): Trigonometric functions for angles (in


radians).

python Copy code


math.sin(math.pi / 2) # Output: 1.0

6. math.pi and math.e: Constants for pi and Euler’s number.

python Copy code


math.pi # Output: 3.141592653589793
math.e # Output: 2.718281828459045

Summary Table of Numeric Data Types and Common Functions

Numer Descrip Exa


ic Type tion mpl
e
int Whole 42, -7
numbers
float Decimal 3.14,
numbers -2.5

compl Complex 2 +
ex numbers 3j

Function Description Example

abs(x) Absolute value abs(-7) ➔7

round(x, n) Round to n decimal places round(3.14159, 2)


➔3.14
pow(x, y) x raised to the power of y pow(2, 3) ➔8

divmod(x, y) Quotient and remainder divmod(10, 3) ➔(3,


1)
Number of bits required to
int.bit_leng (5).bit_length() ➔3
th() represent aninteger

(5.0).is_integer()
float.is_int Checks if a float is a whole number ➔
eger()
True

18
Funct Description Exam
ion ple
math.sqrt Square root of x math.sqrt(16)
(x) ➔4.0
math.log( Natural logarithm of x math.log(10)
x)

math.pi Constant for pi math.pi


➔3.1415...

These methods and functions provide a strong foundation for performing mathematical
operations and managing numeric data in Python.

Numeric Datatypes(Contd),StringsStrings(Contd), Lists

1) Declaration of Strings

2) Methods of Strings
In Python, strings and lists are essential data types for handling and manipulating sequences
of characters and collections of items, respectively. Here’s a breakdown of strings and lists,
including how to declare them and the most common methods used.

Strings in Python

A string in Python is a sequence of characters enclosed within single quotes ('...'), double
quotes ("..."), or triple quotes ('''...''' or """...""" for multi-line strings). Strings are
immutable, meaning that once created, their content cannot be changed.

1. Declaration of Strings
To declare a string, simply assign text to a variable with quotes around it:

python Copy code


# Single-quoted string greeting = 'Hello, World!'

# Double-quoted stringname = "Alice"

# Triple-quoted string for multi-line textmessage = """This is a


multi-line string."""

19
You can use either single or double quotes interchangeably, but triple quotes are typically
usedfor multi-line strings or docstrings in functions and classes.

2. Common String Methods


Python provides a variety of methods to manipulate strings. Here are some commonly used
methods:

a. Changing Case

 str.lower(): Converts all characters in the string to lowercase.

python Copy code


text = "Hello"
print(text.lower()) # Output: "hello"

 str.upper(): Converts all characters to uppercase.

python Copy code


text = "Hello"
print(text.upper()) # Output: "HELLO"

 str.capitalize(): Capitalizes the first character of the string.

python Copy code


text = "hello world"
print(text.capitalize()) # Output: "Hello world"

b. Searching and Replacing

 str.find(substring): Returns the index of the first occurrence of substring in the


string;returns -1 if not found.

python Copy code


text = "hello world" print(text.find("world")) # Output: 6

 str.replace(old, new): Replaces all occurrences of old substring with new substring.

python Copy code


text = "hello world"
print(text.replace("world", "Python")) # Output: "hello Python"

20
c. Checking Content

 str.isdigit(): Returns True if all characters in the string are digits.

python Copy code


text = "12345"
print(text.isdigit()) # Output: True

 str.isalpha(): Returns True if all characters are alphabetic.

python Copy code


text = "Hello"
print(text.isalpha()) # Output: True

 str.isalnum(): Returns True if all characters are alphanumeric (letters or numbers).

python Copy code


text = "Hello123" print(text.isalnum()) # Output: True

d. Splitting and Joining

 str.split(delimiter): Splits a string into a list of substrings based on a specified


delimiter.

python Copy code


text = "apple,banana,cherry"
fruits = text.split(",") # Output: ["apple", "banana", "cherry"]

 str.join(iterable): Joins elements of an iterable (e.g., list) into a single string, with the
string as a separator.

python Copy code


fruits = ["apple", "banana", "cherry"]
result = ", ".join(fruits) # Output: "apple, banana, cherry"

e. Stripping Whitespace

 str.strip(): Removes leading and trailing whitespace from the string.

python Copy code


text = " hello " print(text.strip()) # Output: "hello"

Example Summary of String Methods

21
Meth Description Example
od
str.low Converts to lowercase "Hello".lower()
er() ➔"hello"
str.upp Converts to uppercase "Hello".upper()
er() ➔"HELLO"
str.fin Finds index of substring "hello".find("o") ➔4
d()
str.rep Replaces substring "hello".replace("o",
lace() "a")

str.isd Checks if all characters are "123".isdigit() ➔True


igit() digits
str.spl Splits into list based on "a,b".split(",")
it() delimiter ➔['a','b']

str.joi Joins list into string with ",".join(['a','b'])


n() delimiter ➔"a,b"

Lists in Python

A list is a mutable, ordered collection of items. Lists can hold elements of any data type, and
youcan modify them after creation.

1. Declaration of Lists

Lists are defined using square brackets [], with items separated by commas.

python Copy code


# List of integers numbers = [1, 2, 3, 4, 5]

# List of mixed data types mixed = [1, "hello", 3.14, True]

# Empty list empty_list = []

2. Common List Methods


Python offers several methods to manage and manipulate lists:

a. Adding and Removing Elements

 list.append(element): Adds an element to the end of the list.

python

22
Copy code
numbers = [1, 2, 3]
numbers.append(4) # Output: [1, 2, 3, 4]

 list.insert(index, element): Inserts an element at a specified index.

python Copy code


numbers = [1, 3]
numbers.insert(1, 2) # Output: [1, 2, 3]

 list.remove(element): Removes the first occurrence of an element from the list.

python Copy code


numbers = [1, 2, 3, 2]
numbers.remove(2) # Output: [1, 3, 2]

 list.pop(index): Removes and returns the element at the specified index; if index is
omitted, removes the last element.

python Copy code


numbers = [1, 2, 3]
numbers.pop(1) # Output: [1, 3]

b. Searching and Counting

 list.index(element): Returns the index of the first occurrence of an element.

python Copy code


numbers = [1, 2, 3] print(numbers.index(2)) # Output: 1

 list.count(element): Returns the number of occurrences of an element in the list.

python Copy code


numbers = [1, 2, 2, 3] print(numbers.count(2)) # Output: 2

c. Sorting and Reversing

 list.sort(): Sorts the list in ascending order.

python Copy code


numbers = [3, 1, 2]
numbers.sort() # Output: [1, 2, 3]

 list.reverse(): Reverses the elements of the list.

23
python Copy code
numbers = [1, 2, 3]
numbers.reverse() # Output: [3, 2, 1]

d. Copying and Clearing

 list.copy(): Returns a shallow copy of the list.

python Copy code


copy_numbers = numbers.copy()

 list.clear(): Removes all elements from the list.

python Copy code


numbers.clear() # Output: []

Example Summary of List Methods

Meth Description Example


od
list.app Adds element to the end [1].append(2) ➔[1, 2]
end()

list.ins Inserts element at index [1, 3].insert(1, 2) ➔[1,


ert() 2, 3]

list.rem Removes first occurrence of [1, 2, 2].remove(2) ➔[1,


ove() element 2]

list.pop Removes and returns element [1, 2, 3].pop(1) ➔[1, 3]


() at index
list.sor Sorts elements [3, 1, 2].sort() ➔[1, 2,
t() 3]

list.rev Reverses elements [1, 2, 3].reverse() ➔[3,


erse() 2, 1]

list.cle Removes all elements [1, 2, 3].clear() ➔[]


ar()

Conditions

1) if conditions

2) if else condition

3) elif conditions

24
4) Nested if

In Python, conditional statements allow you to execute code based on certain conditions.
These statements control the flow of the program depending on whether a specific condition
is True or False. The main conditional statements in Python are if, if-else, elif, and
nested if statements.

1. if Condition

The if statement allows you to execute a block of code only if a specified condition is True.

Syntax:
python Copy code
if condition:
# Code block to execute if condition is True

Example:
python Copy codeage = 20
if age >= 18:
print("You are an adult.") # This will be printed since the condition
isTrue

If the condition is True, the code inside the if block will be executed. Otherwise, the program
will move on without executing the block.

2. if-else Condition

The if-else statement provides an alternative execution path. If the condition in the if
statement is True, the block inside the if is executed. If it’s False, the block inside the else
isexecuted.

Syntax:
python Copy code
if condition:
# Code block if condition is Trueelse:
# Code block if condition is False

Example:
python Copy codeage = 16
if age >= 18:
print("You are an adult.")

25
else:
print("You are not an adult.") # This will be printed since the
condition is False

Here, since the condition age >= 18 is False, the code inside the else block is executed.

3. elif Condition

The elif (short for "else if") condition allows you to check multiple conditions in sequence.
If the if condition is False, the program will check the condition in the elif block. You can
havemultiple elif blocks for multiple conditions.

Syntax:
python Copy code
if condition1:
# Code block if condition1 is Trueelif condition2:
# Code block if condition2 is Trueelif condition3:
# Code block if condition3 is Trueelse:
# Code block if no conditions are True

Example:
python Copy codeage = 25
if age >= 65:
print("You are a senior citizen.")elif age >= 18:
print("You are an adult.") # This will be printed because the
conditionis True
else:
print("You are a minor.")

In this example, Python first checks if age >= 65. Since it's False, it checks the next
condition(age >= 18). Since this is True, the message "You are an adult." is printed.

4. Nested if Conditions

You can place if statements inside other if statements. This is known as nested if. It allows
youto check additional conditions within a particular block if the first condition is True.

Syntax:
python

26
Copy code
if condition1:
if condition2:
# Code block if both condition1 and condition2 are Trueelse:
# Code block if condition1 is True and condition2 is False
else:
# Code block if condition1 is False

Example:
python Copy codeage = 20
has_id = True

if age >= 18:


if has_id:
print("You can enter the club.") # This will be printed because
bothconditions are True
else:
print("You cannot enter the club. ID required.")
else:
print("You are not allowed to enter the club.")

Here, Python first checks if age >= 18. If this condition is True, it checks whether has_id
is True inside the nested if block. If both conditions are met, the message "You can enter
theclub." is printed.

Summary of Conditional Statements

Sta Description Example


te
me
nt
Executes a block of code if the
if if age >= 18: print("Adult")
condition is
True.
Executes one block of code if the if age >= 18: print("Adult")
if
condition is True, otherwise else:print("Minor")
-
el another.
se
Checks multiple conditions,
if age >= 65: print("Senior")
el executes corresponding block if the
elifage >= 18: print("Adult")
if condition isTrue.

if statement inside another if to if age >= 18: if has_id:


Nes checkmore conditions. print("Can Enter") else:
ted print("ID Needed")
if

27
These conditional statements help control the flow of execution in Python programs and are
crucial for making decisions based on variable values or user input.

Python Datatypes: Dictionaries,Loops and loop control statements Python

for Loop Python while Loop

Python break and continuePython pass Statement


In Python, dictionaries are used to store data in key-value pairs, while loops are used to
repeat a block of code multiple times. Loop control statements like break, continue, and
pass allowyou to control the behavior of loops in more sophisticated ways.

1. Dictionaries in Python
A dictionary in Python is an unordered collection of data in the form of key-value pairs. The
keys must be unique and immutable (e.g., strings, numbers, tuples), but the values can be of
anydata type.

Declaration of a Dictionary

A dictionary is defined using curly braces {}, with keys and values separated by a colon (:),
andpairs separated by commas.

Example:
python Copy code
# A dictionary with keys as names and values as agesperson = {
"Alice": 25,
"Bob": 30,
"Charlie": 35
}

Common Dictionary Methods

 dict.keys(): Returns a list of all keys in the dictionary.

python Copy code


print(person.keys()) # Output: dict_keys(['Alice', 'Bob', 'Charlie'])

 dict.values(): Returns a list of all values in the dictionary.

28
python Copy code
print(person.values()) # Output: dict_values([25, 30, 35])

 dict.items(): Returns a list of tuples containing key-value pairs.

python Copy code


print(person.items()) # Output: dict_items([('Alice', 25), ('Bob',
30), ('Charlie', 35)])

 dict.get(key): Returns the value for the specified key, or None if the key does not exist.

python Copy code


print(person.get("Alice")) # Output: 25

2. Loops in Python
Loops allow you to repeat a block of code multiple times. Python supports two types of
loops:
for and while.

Python for Loop

The for loop in Python is used to iterate over a sequence (like a list, tuple, string, or
dictionary)or other iterable objects.

Syntax:
python Copy code
for variable in iterable:
# Code block to be executed

Example:
python Copy code
# Loop through a list
fruits = ["apple", "banana", "cherry"]for fruit in fruits:
print(fruit)

Output:

Copy codeapple banana cherry

In this example, the for loop iterates through each element in the fruits list and prints them.

29
Python while Loop

The while loop in Python repeats a block of code as long as a given condition is True.

Syntax:
python Copy code
while condition:
# Code block to be executed

Example:
python Copy code
# Print numbers from 1 to 5count = 1
while count <= 5:print(count)count += 1

Output:

Copy code1
2
3
4
5

In this example, the loop runs as long as the count is less than or equal to 5. After each
iteration,
count is incremented by 1.

3. Loop Control Statements


Loop control statements allow you to change the behavior of a loop in various ways. These
include break, continue, and pass.

break Statement

The break statement is used to exit the loop prematurely, even if the loop condition is still
True.

Example:
python Copy code
# Break out of a loop when number 3 is foundfor num in range(5):
if num == 3:break
print(num)

30
Output:

Copy code0
1
2

In this example, when num equals 3, the loop is immediately terminated due to the break
statement, and no further numbers are printed.

continue Statement

The continue statement skips the current iteration of the loop and moves on to the next
iteration. It is used when you want to skip specific conditions within a loop but continue the
loopotherwise.

Example:
python Copy code
# Skip printing the number 3for num in range(5):
if num == 3:
continue print(num)

Output:

Copy code0
1
2
4

In this example, when num equals 3, the continue statement is executed, and the number 3 is
skipped, but the loop continues for other numbers.

pass Statement

The pass statement is a placeholder that does nothing. It is used when you need a statement
syntactically, but don't want to execute any code. It's useful for creating empty functions,
classes,or loops.

Example:
python Copy code
# Empty loop that does nothingfor num in range(5):
pass

In this case, the pass statement prevents any action from occurring in the loop body.

31
Summary of Loop Control Statements

Sta Description Example


te
me
nt
Exits the loop immediately, regardless for num in range(5): if num
br
ea of thecondition. == 3:break
k
Skips the current iteration and moves for num in range(5): if num
co
nt to thenext iteration. == 3:continue
in
ue
Does nothing, used as a placeholder or
pa inempty loop bodies. for num in range(5): pass
ss

Summary

 Dictionaries store key-value pairs and provide methods like get(), keys(), values(), and
items() for accessing data.
 for loop iterates over a sequence or iterable, while the while loop repeats code based on a
condition.
 Loop control statements like break, continue, and pass allow you to manage loop
execution flow. break exits a loop, continue skips an iteration, and pass is a no-op
placeholder.

These features are essential for controlling program flow and managing data in Python
programs.

Python Functions

1) Python Function Arguments

2) Python Variable Scope

3) Python Global Keyword

4) Python Recursion

5) Python Modules

6) Python Package
32
In Python, functions are used to encapsulate code into reusable blocks. Python provides several
features and concepts related to functions, such as arguments, variable scope, recursion,
modules, and packages, which help you write modular and efficient code.

1. Python Function Arguments


In Python, function arguments are the values passed to a function when it is called.
Functionscan accept different types of arguments:

a. Positional Arguments

Positional arguments are passed to a function in a specific order. The function receives them
inthe same order they are defined.

Example:
python Copy code
def greet(name, age):
print(f"Hello {name}, you are {age} years old.") greet("Alice", 25) #

Output: Hello Alice, you are 25 years old.

b. Keyword Arguments

Keyword arguments are passed to a function by explicitly specifying the parameter names.
Thisallows you to pass arguments in any order.

Example:
python Copy code
def greet(name, age):
print(f"Hello {name}, you are {age} years old.")

greet(age=25, name="Bob") # Output: Hello Bob, you are 25 years old.

c. Default Arguments

You can specify default values for function arguments. If the caller does not provide a value
forthose arguments, the default value is used.

Example:
python Copy code
def greet(name, age=18):
print(f"Hello {name}, you are {age} years old.")

33
greet("Charlie") # Output: Hello Charlie, you are 18 years old.
greet("David", 30) # Output: Hello David, you are 30 years old.

d. Variable-Length Arguments

 *args allows you to pass a variable number of positional arguments to a function.


 **kwargs allows you to pass a variable number of keyword arguments.

Example:
python Copy code
def greet(*names):
for name in names: print(f"Hello {name}")

greet("Alice", "Bob", "Charlie") # Output: Hello Alice, Hello Bob, Hello


Charlie
python Copy code
def display_info(**info):
for key, value in info.items():print(f"{key}: {value}")

display_info(name="Alice", age=25, city="New York")# Output:


# name: Alice# age: 25
# city: New York

2. Python Variable Scope


In Python, variable scope refers to the region of the program where a variable can be
accessed.There are two main types of variable scopes:

a. Local Scope

A variable is local if it is defined inside a function. It can only be accessed within that
function.

python Copy code


def my_function():
x = 10 # Local variableprint(x)

my_function() # Output: 10
# print(x) # This would result in an error because x is local to
my_function

34
b. Global Scope

A variable is global if it is defined outside of any function. It can be accessed from anywhere
inthe program.

python Copy code


x = 20 # Global variable

def my_function():
print(x) # Accessing global variablemy_function() # Output: 20

3. Python global Keyword

The global keyword is used to indicate that a variable defined outside a function is being
modified inside the function. Without global, Python will treat any assignment to a variable
inside a function as a local variable.

Example:
python Copy code
x = 10 # Global variable

def modify_global():global x
x = 20 # Modifies the global variable

modify_global() print(x) # Output: 20

Without the global keyword, x would be considered a local variable inside


modify_global().

4. Python Recursion
Recursion occurs when a function calls itself. This is a powerful concept, but it must have a
basecase to stop the recursive calls, otherwise, it will result in infinite recursion.

Example of Recursion (Factorial Function):


python Copy code
def factorial(n):
if n == 0: # Base casereturn 1
else:
return n * factorial(n - 1)

35
print(factorial(5)) # Output: 120

In this example, the factorial function calls itself until it reaches the base case (n == 0).

5. Python Modules

A module is a file containing Python definitions and statements. You can use the import
statement to include the functionality of one module into another. This helps in organizing
yourcode and reusing code across different programs.

Example:

Consider a file called math_operations.py:

python Copy code


# math_operations.py def add(a, b):
return a + b

def subtract(a, b):return a - b

You can import and use this module in another Python file:

python Copy code# main.py


import math_operations

result = math_operations.add(5, 3)print(result) # Output: 8

You can also import specific functions:

python Copy code


from math_operations import add

result = add(5, 3) print(result) # Output: 8

6. Python Packages
A package is a collection of Python modules grouped together in a directory hierarchy.
Packagesallow for a better organization of code, especially in larger projects.

36
A package is simply a directory containing modules and a special file named init .py.

Example:

Consider a directory structure like this:

markdown Copy codemy_package/


init .py math_operations.py string_operations.py

You can import modules from this package like this:

python Copy code


from my_package import math_operations
from my_package.string_operations import reverse_string

7. Python Main Function

In Python, there isn't a built-in main() function like in some other languages (e.g., C, Java).
However, it is common practice to define a function main() and call it when the script is
executed directly.

To achieve this, we use the if name == " main ": construct to ensure that code
inside
main() only runs when the script is executed directly (not when imported as a module).

Example:
python Copy code def main():
print("This is the main function.")

if name == " main ":main()

 name is a special variable in Python. If the Python file is being run directly, name
will be set to " main ", and the code inside if name == " main ": will be
executed.
 If the file is imported as a module, the code inside this block will not execute.

37
Summary of Functions in Python

Con Description Example


cept
Functio Values passed to a function when called.
def greet(name,
n Includes positional, keyword, and default age=18):
Argume arguments.
nts
Refers to where variables can be accessed x = 10(global), def
Variabl
(local orglobal scope). func():x = 5 (local)
e Scope

Global global x inside a


Used to modify a global variable inside a
Keywor function to modify a global
function.
d x.

A function that calls itself to solve a problem.


Recursi factorial(n)
Musthave a base case.
on

Files containing Python code that can be


Module import
importedinto other programs. math_operations
s

A collection of modules grouped together in from my_package


Packag
directories. import
es
math_operations

A common practice to define a main() if name ==


Main
function and run it using if name == " " main ": main()
Functio
main ":.
n

These concepts form the foundation for organizing and structuring Python programs
effectively. Functions allow for modularity and code reuse, and understanding scopes,
recursion, and modules can greatly improve code quality and readability.

Python Files

1) Python Directory and Files Management

2) Python CSV: Read and Write CSV files

3) Reading CSV files in Python

4) Writing CSV files in Python


In Python, file handling is essential for working with external files, such as reading from or
writing to text files, CSV files, and more. This section covers how to manage directories and
files in Python, as well as how to work with CSV files using the built-in csv module.
38
1. Python Directory and Files Management
Python provides various functions and modules to manage directories and files, allowing you
tocreate, delete, rename, and organize files within the file system.

a. Working with Directories

 os Module: The os module provides functions for interacting with the file system.
o Create a directory:

python Copy codeimport os


os.mkdir("new_directory") # Creates a directory named
'new_directory'

o Change the current working directory:

python Copy code


os.chdir("new_directory") # Change to the 'new_directory'

o Get the current working directory:

python Copy code


current_directory = os.getcwd() # Returns the current working
directory
print(current_directory)

o List files and directories:

python Copy code


files = os.listdir() # Returns a list of files and directories
in the current directory
print(files)

o Remove a directory:

python Copy code


os.rmdir("new_directory") # Removes the directory (must be
empty)

39
b. Working with Files

 open() Function: Python provides the open() function to work with files. You can
opena file in various modes: r (read), w (write), a (append), b (binary), etc.
o Open a file for reading:

python Copy code


file = open("example.txt", "r") # Open for reading
content = file.read() # Read the entire content of the file
print(content)
file.close() # Always close the file after use

o Open a file for writing:

python Copy code


file = open("example.txt", "w") # Open for writing (creates a
new file or overwrites)
file.write("Hello, Python!") # Write to the filefile.close()

o Open a file for appending:

python Copy code


file = open("example.txt", "a") # Open for appending
file.write("\nAppending new line.")
file.close()

o Checking if a file exists:

python Copy codeimport os


if os.path.exists("example.txt"):print("File exists.")
else:
print("File does not exist.")

2. Python CSV: Read and Write CSV Files


The CSV (Comma Separated Values) format is commonly used for storing tabular data.
Python provides a built-in csv module to work with CSV files easily. This module allows for
reading and writing CSV data into a file.

40
3. Reading CSV Files in Python

You can use the csv.reader method to read data from a CSV file. This method returns each
rowas a list of strings.

Example:
python Copy codeimport csv

# Open the CSV file for reading


with open("data.csv", mode="r") as file:csv_reader = csv.reader(file)

# Iterate through each rowfor row in csv_reader:


print(row) # Each row is a list of values

Explanation:

 open("data.csv", mode="r"): Opens the file data.csv for reading.


 csv.reader(file): Creates a CSV reader object that can iterate over each row.
 for row in csv_reader: Loops through the rows, where row is a list of values from each
line in the CSV file.

If the file has headers (column names) in the first row, you can skip them using next():

python
Copy code
with open("data.csv", mode="r") as file: csv_reader = csv.reader(file)
next(csv_reader) # Skip the header rowfor row in csv_reader:
print(row)

4. Writing CSV Files in Python

You can use the csv.writer method to write data to a CSV file. This method allows you to
write rows of data to a CSV file.

Example:
python Copy codeimport csv

# Data to be written to the CSV filedata = [["Name", "Age", "City"],


["Alice", 30, "New York"],
["Bob", 25, "San Francisco"],
["Charlie", 35, "Los Angeles"]]

41
# Open the CSV file for writing
with open("output.csv", mode="w", newline="") as file: csv_writer =
csv.writer(file)

# Write each row to the CSV filefor row in data:


csv_writer.writerow(row)

Explanation:

 open("output.csv", mode="w", newline=""): Opens the file output.csv for


writing. The newline="" argument ensures that no extra newlines are added between rows
(especiallyuseful in Windows).
 csv.writer(file): Creates a CSV writer object that writes data to the file.
 csv_writer.writerow(row): Writes a row (list) to the CSV file.

If you have a dictionary of data and want to write it to a CSV file, you can use

csv.DictWriter:python
Copy codeimport csv

# Data to be written as a dictionary


data = [{"Name": "Alice", "Age": 30, "City": "New York"},
{"Name": "Bob", "Age": 25, "City": "San Francisco"}]

# Open the CSV file for writing


with open("output_dict.csv", mode="w", newline="") as file: fieldnames =
["Name", "Age", "City"] # Define the column names csv_writer =
csv.DictWriter(file, fieldnames=fieldnames)

# Write the header csv_writer.writeheader()

# Write the rows from the dictionaryfor row in data:


csv_writer.writerow(row)

Explanation:

 csv.DictWriter(file, fieldnames=fieldnames): Creates a CSV writer object that


canwrite dictionaries to the file.
 csv_writer.writeheader(): Writes the header row (the column names).
 csv_writer.writerow(row): Writes a row from a dictionary.

Python Exception Handling

1) Python Exceptions

2) Python Exception Handling

42
3) Python Custom Exceptions

Python Exception Handling


Exception handling in Python is a mechanism to handle runtime errors, so the program doesn't
crash. It allows you to catch and handle errors gracefully, providing better control over the
program flow.

1. Python Exceptions
An exception is an event that disrupts the normal flow of a program. When Python
encounters an error (or an exception), it stops executing the current block of code and jumps
to the nearestexception handler (if one exists).

 Built-in Exceptions: Python has a set of built-in exceptions that are raised for common errors,
such as:
o ZeroDivisionError: Raised when dividing by zero.
o ValueError: Raised when an operation or function receives an argument of the
righttype but inappropriate value.
o TypeError: Raised when an operation or function is applied to an object of
inappropriate type.
o FileNotFoundError: Raised when an attempt to open a file fails because the file
cannot be found.
o IndexError: Raised when an index is out of range for a list or tuple.

Example:
python Copy code
# Example of some common exceptionstry:
x = 10 / 0 # Division by zeroexcept ZeroDivisionError as e:
print(f"Caught an exception: {e}") # Output: Caught an exception:
division by zero

try:
number = int("abc") # Invalid literal for intexcept ValueError as e:
print(f"Caught an exception: {e}") # Output: Caught an exception:
invalid literal for int() with base 10: 'abc'

2. Python Exception Handling

Python provides a try, except, else, and finally block to handle exceptions effectively.

43
a. try Block

The code that might raise an exception is placed inside the try block. If an exception occurs,
thecode in the except block is executed.

b. except Block

The except block catches the exception and allows you to handle it. You can also specify
whichexception you want to catch.

c. else Block

If no exception occurs, the else block will be executed. This block is optional.

d. finally Block

The finally block is always executed, whether an exception occurs or not. It's usually used
forclean-up actions, such as closing files or releasing resources.

Syntax:
python Copy codetry:
# Code that might raise an exceptionresult = 10 / 2
except ZeroDivisionError as e:
# Code that runs if an exception occursprint(f"Error: {e}")
else:
# Code that runs if no exception occurs print("Division was
successful!")
finally:
# Code that runs no matter what print("This will always execute.")

Example:
python Copy codetry:
file = open("non_existing_file.txt", "r") # Trying to open a file that
doesn't exist
except FileNotFoundError as e:
print(f"Caught an exception: {e}") # Caught an exception: [Errno 2] No
such file or directory: 'non_existing_file.txt'
else:
print("File opened successfully!")finally:
print("Cleaning up resources...")

44
Output:

yaml Copy code


Caught an exception: [Errno 2] No such file or directory:
'non_existing_file.txt'
Cleaning up resources...

 If no exception is raised, the else block is executed.


 The finally block will always execute, even if an exception is raised.

3. Python Custom Exceptions


In addition to the built-in exceptions, you can define your own custom exceptions in Python.
A custom exception class is created by subclassing the built-in Exception class or any of its
subclasses.

a. Creating a Custom Exception

To create a custom exception, define a new class that inherits from the Exception class. You
canalso customize the error message by overriding the init method.

Example:
python Copy code
# Define a custom exception classclass CustomError(Exception):
def init (self, message): self.message = message super(). init
(self.message)

# Raise the custom exceptiontry:


raise CustomError("Something went wrong!")except CustomError as e:
print(f"Caught a custom exception: {e}") # Output: Caught a custom
exception: Something went wrong!

In this example:

 We define a class CustomError that inherits from the Exception class.


 The custom exception is raised using the raise keyword, and it is caught and handled in the
except block.

45
b. Using Custom Exception for Validation

Custom exceptions are especially useful when validating data or creating specific error
handlinglogic.

python Copy code


# Define a custom exception for invalid age class
InvalidAgeError(Exception):
pass

def check_age(age):if age < 18:


raise InvalidAgeError("Age must be 18 or older.")else:
print("Age is valid.")

try:
check_age(16)
except InvalidAgeError as e:
print(f"Caught an exception: {e}") # Output: Caught an exception: Age
must be 18 or older.

In this example, the custom exception InvalidAgeError is raised when the age is less than
18.

Classes & Objects

1) Python Object and Class

2) Python Objects and Classes

3) Python Inheritance

4) Python Multiple Inheritance

5) Polymorphism in Python

6) Python Operator Overloading

Classes & Objects in Python


In Python, Classes and Objects are fundamental concepts in object-oriented programming
(OOP). They allow you to create your own data types and structures to organize code in a way
that models real-world entities and their behaviors.

46
1. Python Object and Class

a. What is a Class?

A class in Python is a blueprint for creating objects (instances). It defines a set of attributes
andmethods that the created objects will share.

 A class is like a template.


 Attributes are variables that belong to a class (also known as properties).
 Methods are functions that belong to a class (functions inside a class).

b. What is an Object?

An object is an instance of a class. When you create an object from a class, the class acts as a
template to define the object’s attributes and methods.

Creating a Class and Object

Here’s how you define a class and create an object in Python:

python Copy code


# Define a classclass Car:
# Constructor ( init ) to initialize object attributes def init
(self, make, model, year):
self.make = make self.model = modelself.year = year

# Method to display informationdef display_info(self):


print(f"{self.year} {self.make} {self.model}")

# Create an object (instance) of the Car class my_car = Car("Toyota",


"Corolla", 2020)

# Call method on the object


my_car.display_info() # Output: 2020 Toyota Corolla

 The init method is the constructor used to initialize the object’s attributes.
 The display_info method is a regular function that prints details about the car.

2. Python Objects and Classes


In Python, an object is created from a class. You can have multiple objects from the same
class,and each object will have its own attributes (data).

47
Example:
python Copy codeclass Dog:
def init (self, name, breed):self.name = name self.breed = breed

def speak(self): print(f"{self.name} says Woof!")

# Create two objects of the Dog class dog1 = Dog("Buddy", "Golden


Retriever")dog2 = Dog("Max", "Bulldog")

# Call methods on objects


dog1.speak() # Output: Buddy says Woof! dog2.speak() # Output: Max says
Woof!

 Both dog1 and dog2 are instances of the Dog class, but they have different name and breed
attributes.

3. Python Inheritance
Inheritance allows a class (child class) to inherit the attributes and methods of another class
(parent class). This enables you to create a new class that is a modified version of an existing
class.

Syntax:
python Copy code
class ChildClass(ParentClass):
# Additional attributes and methods

Example:
python Copy code
# Parent classclass Animal:
def init (self, name):self.name = name

def speak(self):
print(f"{self.name} makes a sound")

# Child class inheriting from Animalclass Dog(Animal):


def init (self, name, breed):
super(). init (name) # Call the constructor of the parent class
self.breed = breed

48
def speak(self): print(f"{self.name} barks")

# Create an object of the Dog class dog = Dog("Buddy", "Golden Retriever")


dog.speak() # Output: Buddy barks

 The Dog class inherits from the Animal class, and it can call methods from Animal, but it
canalso override methods (like speak) to provide its own implementation.

4. Python Multiple Inheritance


Python supports multiple inheritance, which means a class can inherit from more than one
class. This allows you to combine functionalities from multiple parent classes.

Example:
python Copy code
# Parent class 1class Animal:
def init (self, name):self.name = name

def speak(self):
print(f"{self.name} makes a sound")

# Parent class 2class Canine:


def init (self, breed):self.breed = breed

def is_canine(self):return True

# Child class inheriting from both Animal and Canine class Dog(Animal,
Canine):
def init (self, name, breed):
Animal. init (self, name) # Initialize Animal part Canine. init
(self, breed) # Initialize Canine part

# Create an object of Dog


dog = Dog("Buddy", "Golden Retriever") dog.speak() # Output: Buddy makes a
soundprint(dog.is_canine()) # Output: True

 The Dog class inherits from both Animal and Canine, meaning it can use methods from
bothparent classes.

49
5. Polymorphism in Python
Polymorphism means "many forms." It allows different classes to define the same method in
different ways. In Python, polymorphism is achieved by method overriding or by defining
methods with the same name across different classes.

Example:
python Copy code
# Parent classclass Animal:
def speak(self): print("Animal speaks")

# Child class 1 class Dog(Animal):


def speak(self): print("Dog barks")

# Child class 2 class Cat(Animal):


def speak(self): print("Cat meows")

# Create objectsanimal = Animal()dog = Dog()


cat = Cat()

# Call the speak method on each object animal.speak() # Output: Animal


speaksdog.speak() # Output: Dog barks cat.speak() # Output: Cat
meows

 The speak method is defined in all classes, but each class implements it in its own way
(overrides the method).

Polymorphism allows you to call the same method on different objects and get different
behaviors depending on the object's class.

6. Python Operator Overloading

Operator overloading allows you to define how operators (like +, -, *, etc.) behave for
objects of a class. Python allows you to override the behavior of operators for user-defined
classes.

Example: python Copy code


class Point:

50
def init (self, x, y):self.x = x
self.y = y

# Overloading the + operator to add two Point objects def add (self,
other):
return Point(self.x + other.x, self.y + other.y)

# String representation of the objectdef str (self):


return f"Point({self.x}, {self.y})"

# Create two Point objectspoint1 = Point(1, 2) point2 = Point(3, 4)

# Use the overloaded + operator


result = point1 + point2 # Calls the add method print(result) # Output:
Point(4, 6)

 The add method is used to overload the + operator, allowing us to add two Point objects
together.
 The str method is used to define how to print the object.

Summary

Concep Description
t
Class A blueprint for creating objects. Defines attributes and methods.

Object An instance of a class. Has its own data and can use class methods.

Inheritance A mechanism to create a new class using an existing class (parent class).

Multiple A class can inherit from more than one class.


Inheritance
Polymorphism A concept where different classes can define the same method in different
ways.
Operator Allows customizing the behavior of operators like +, -, * for class objects.
Overloading

Conclusion about Python


Python is a powerful, versatile, and user-friendly programming language that has become one
of the most popular languages in the world. It’s known for its simplicity and readability,
making it ideal for beginners while still being robust enough for advanced programmers and
developers.

51
Here are some key takeaways:

1. Easy to Learn and Use: Python’s syntax is clear, concise, and close to natural
language, which makes it easy to read and write code. This simplicity accelerates the
development process and reduces the chances of errors.
2. Versatility: Python can be used for a wide range of applications, from web
development and data analysis to scientific computing, machine learning, artificial
intelligence, and automation. This versatility makes Python a go-to language for
developers across variousfields.
3. Extensive Libraries and Frameworks: Python offers a wealth of libraries and
frameworks that extend its capabilities. Whether you’re working with data science
(e.g., Pandas, NumPy), web development (e.g., Django, Flask), or machine learning
(e.g., TensorFlow, Scikit-learn), Python’s ecosystem has a tool for almost every
task.
4. Strong Community Support: Python has a large, active community that constantly
contributes to its growth. This ensures a wealth of tutorials, forums, and
documentation, making it easy to get help and stay up-to-date with the latest
developments.
5. Cross-platform Compatibility: Python runs on all major platforms (Windows,
macOS,Linux), allowing developers to create applications that are easily portable.
6. Integration and Extensibility: Python can be integrated with other languages and
platforms. It can interact with C, C++, Java, and more, making it a versatile tool for
integrating with existing systems.
7. Object-Oriented and Functional: Python supports both Object-Oriented
Programming (OOP) and Functional Programming paradigms, allowing
developers tochoose the most appropriate approach for their projects.
8. Simplicity, but Powerful: Python is simple enough for beginners to grasp quickly,
but it is also powerful enough to be used in large-scale applications by experienced
developers.

52

You might also like