Python Django Internship Report 5 - Pagenumber
Python Django Internship Report 5 - Pagenumber
BACHELOR OF TECHNOLOGY
IN
COMPUTER SCIENCE & ENGINEERING
Submitted by
BADINENI SIVASAIKRISHNA
21F91A0593
A.Y : 2024-2025
1
PRAKASAM ENGINEERING COLLEGE
(An ISO 9001-2008 & NAAC Accredited Institution)
DEPARTMENTOF
COMPTER SCIENCE & ENGINEERING
BONAFIDE CERTIFICATE
This is to certify that the Internship report entitled “ PYTHON DJANGO” is a bonafide
2
3
ACKNOWLEDGEMENT
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 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. Variables
2. Keywords
3. Datatypes
Numeric Datatypes
1. Declaration Of Strings
2. Methods Of Strings
Lists
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
Exception Handling
1. Exceptions
2. Exception Handing
3. Custom Exceptions
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.
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.
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.
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.
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.
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.
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:
This should display the installed Python version, confirming the installation.
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.
o Fedora:
11
o Arch Linux:
If not installed, you can install it manually by following pip installation instructions.
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:
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.
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.
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
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.
Example:
python Copy code
if True: # `if` and `True` are keywordsprint("Hello")
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
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.
# 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:
3. pow(): Returns the value of a number raised to a specified power, equivalent to base
**exponent.
4. divmod(): Returns a tuple containing the quotient and remainder when dividing two
numbers.
16
5. int.bit_length(): Returns the number of bits required to represent an integer in
binary.
7. complex.real and complex.imag: Access the real and imaginary parts of a complex
number.
The math module in Python provides additional functions specifically for numeric operations,
particularly useful for floating-point calculations:
17
4. math.log(): Returns the natural logarithm (base eee) of a number. Use math.log(x,
base) for custom bases.
compl Complex 2 +
ex numbers 3j
(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)
These methods and functions provide a strong foundation for performing mathematical
operations and managing numeric data in Python.
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:
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.
a. Changing Case
str.replace(old, new): Replaces all occurrences of old substring with new substring.
20
c. Checking Content
str.join(iterable): Joins elements of an iterable (e.g., list) into a single string, with the
string as a separator.
e. Stripping Whitespace
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")
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
22
Copy code
numbers = [1, 2, 3]
numbers.append(4) # Output: [1, 2, 3, 4]
list.pop(index): Removes and returns the element at the specified index; if index is
omitted, removes the last element.
23
python Copy code
numbers = [1, 2, 3]
numbers.reverse() # Output: [3, 2, 1]
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
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.
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.
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
}
28
python Copy code
print(person.values()) # Output: dict_values([25, 30, 35])
dict.get(key): Returns the value for the specified key, or None if the key does not exist.
2. Loops in Python
Loops allow you to repeat a block of code multiple times. Python supports two types of
loops:
for and while.
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:
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.
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
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
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.
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) #
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.")
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
Example:
python Copy code
def greet(*names):
for name in names: print(f"Hello {name}")
a. Local Scope
A variable is local if it is defined inside a function. It can only be accessed within that
function.
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.
def my_function():
print(x) # Accessing global variablemy_function() # Output: 20
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
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.
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:
You can import and use this module in another Python file:
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:
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.")
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
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
os Module: The os module provides functions for interacting with the file system.
o Create a directory:
o Remove a directory:
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:
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
Explanation:
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)
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
41
# Open the CSV file for writing
with open("output.csv", mode="w", newline="") as file: csv_writer =
csv.writer(file)
Explanation:
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
Explanation:
1) Python Exceptions
42
3) Python Custom Exceptions
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'
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:
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)
In this example:
45
b. Using Custom Exception for Validation
Custom exceptions are especially useful when validating data or creating specific error
handlinglogic.
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.
3) Python Inheritance
5) Polymorphism in Python
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.
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.
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.
47
Example:
python Copy codeclass Dog:
def init (self, name, breed):self.name = name self.breed = breed
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")
48
def speak(self): print(f"{self.name} 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.
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")
# 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
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")
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.
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.
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)
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).
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