ADITYA DOCUMENT Voice Assistant
ADITYA DOCUMENT Voice Assistant
DIPLOMA IN
COMPUTER ENGINEERING
Submitted By
i|Page
ADITYA COLLEGE OF ENGINEERING &
TECHNOLOGY
(POLYTECHNIC -249)
SURAMPALEM
DEPARTMENT OF COMPUTER ENGINEERING
CERTIFICATE
PIN.NO……………………………… Mr/Miss………..……….....……….…….…………. of
final year DCME branch along with his/her batch mates submitted in partial fulfilment of the
of Technical Education & Training, T.S., Hyderabad during the academic year 2024-2025.
External Signature
ii | P a g e
ACKNOWLEDGEMENT
We wish to express our deep gratitude to our honorable principal Sri. A.V. MADHAVA
RAO, for providing us with necessary department facilities in completion of our project.
We would like to express our sincere gratitude to Sri. VIJAYA DURGA, Head of the
department of Computer Engineering, Aditya College, for permitting us to do Industrial
training at TECHIN-IT, HYDERABAD and for his/her encouragement, guidance and
valuable suggestions which are of utmost importance in successful completion of the
industrial training.
We express our deep sense of gratitude and heartful thanks to Sri. G. SRINIVASA RAO,
M.D, TECHIN-IT, HYDERABAD.
Lastly, we convey our profound thanks to all the employees working at TECHIN-IT,
HYDERABAD.
iii | P a g e
ABSTRACT
1|Page
INDEX
SNO NAME OF THE CONTENT PG.NO
1 Abstract 1
2 Index 2
3 Introduction to PYTHON and Installation 3-4
4 Working with Python – Python code execution & modes 5-7
5 Python Data types 7-13
6 Variables in Python 14
7 Multi assignments 15
8 Expressions in Python 16-17
9 Identifiers, Literals, Operators 17-18
10 Comments in Python 19-21
11 Modules in Python 21-23
12 Functions in Python & Scope of variables 24-26
13 Recursion Function 27-28
14 Conditional Statements and Looping Statements with some examples 29-32
15 Break, Continue, Pass statements 33-36
16 Arrays and its Operations and methods , common type codes 38-41
17 Lists, Tuples, Dictionaries and its Operations 41-43
18 OOP’s Concepts 44-51
19 Python Modules and Procedures 51-54
20 MetaCharacters in RegEx 55-57
21 Python PIP and its Installation 57-58
22 Python Exception Handling 59-60
23 Python file I/O Operations & Modes 60-61
24 HANDS ON PROJECT 62-65
2|Page
INTRODUCTION TO PYTHON AND INSTALLATION
What is Python?
Python is a popular, general-purpose, high-level programming language. It was
created by Guido van Rossum and first released in 1991. Python is known for its simple
syntax, making it easy to read and write. It allows programmers to express ideas with fewer
lines of code, making development faster and more efficient.
Python Versions:
Python has two main versions:
1. Python 2: Released on October 16, 2000. It's no longer supported as of January
2020.
2. Python 3: Released on December 3, 2008. It’s the current version, recommended for
beginners.
Key Difference: Python 3 fixed many issues in Python 2, making it more efficient.
Therefore, it's better to learn Python 3.
3|Page
2. Installing Python Locally:
It’s recommended to install Python on your computer. Here’s how:
Step-by-Step Installation Guide:
For Windows:
1. Visit the official Python website: python.org/downloads.
4|Page
sudo apt install python3
5|Page
Python is free to download, install, and use.
It is open-source, meaning the community can contribute to its development and
extend its features.
4. Dynamic Typing:
Python uses dynamic typing, meaning you don't need to declare variable types
explicitly.
Example:
x=5 # x is an integer
x = "Hello" # Now, x is a string
7. Portability:
Python programs can run on various platforms like Windows, macOS, Linux, etc.,
without modification.
As long as a compatible Python interpreter is installed, the code runs identically
across platforms.
8. Interpreted Language:
Python is an interpreted language, which means the code is executed line by line.
No intermediate compilation is required, leading to faster development and easier
debugging.
6|Page
9. Interactive Language:
Python can be used interactively through the Python interpreter.
You can write and test code line by line, making it excellent for quick experiments
and learning.
greet("Alice")
7|Page
Python Execution Flow:
PVM
m.pyc
m.py
>>> x = [0, 1, 2]
>>> x
[0, 1, 2]
2+3
5
8|Page
The >>> symbol is a prompt indicating that the interpreter is ready for input.
The results are displayed immediately after entering the command.
2. Script Mode:
In script mode, you write your Python code in a file with a .py extension.
You can execute the entire script at once, which is useful for writing larger programs.
Steps to Run a Python Script:
1. Create a Python file (example.py) and write the code:
# example.py
print("Hello from Script Mode!")
2. Save the file and navigate to its directory using Command Prompt or Terminal.
3. Run the script:
python example.py
Output:
Hello from Script Mode!
9|Page
3. Boolean (bool)
4. String (str)
1. Integer (int):
Integers are whole numbers (positive, negative, or zero) without any decimal point.
In Python, integers can be of unlimited length, limited only by the available memory.
Examples:
a = 10
b = -25
c = 24656354687654
print(a) # Output: 10
print(b) # Output: -25
print(c) # Output: 24656354687654
10 | P a g e
3. Boolean (bool):
Booleans represent True or False values.
Used in comparison operations and conditional statements.
Examples:
a = True
b = False
print(a) # Output: True
print(b) # Output: False
4. String (str):
Strings are sequences of characters enclosed in single (' '), double (" "), or triple
quotes (''' ''' / """ """).
Strings can contain letters, numbers, symbols, and spaces.
Python treats both single and double quotes the same.
Examples:
name = "Python"
college = 'TECHIN IT College'
print(name) # Output: Python
print(college) # Output: TECHIN IT College
11 | P a g e
Empty String Example:
empty_string = ""
print(empty_string) # Output: (blank line)
print(type(empty_string)) # Output: <class 'str'>
Verifying Data Types:
In Python, you can use the type() function to check the data type of a value or
variable.
Examples:
print(type(10)) # <class 'int'>
print(type(3.14)) # <class 'float'>
print(type(True)) # <class 'bool'>
print(type("Hello")) # <class 'str'>
Summary Table:
12 | P a g e
Literal double quote (")
\" "He said, \"Hello!\"" He said, "Hello!"
inside a string
"Path: C:\\ Path: C:\
\\ Literal backslash (\)
new_folder" new_folder
Newline — moves to
\n "Hello\nWorld" Hello<br>World
the next line
Tab space — adds a
\t "Name:\tJohn" Name: John
horizontal tab
Carriage return —
\r returns to the "Hello\rWorld" World
beginning of the line
Backspace — removes
\b "Helloo\b" Hello
the last character
Form feed — moves to Hello (page
\f "Hello\fWorld"
the next page break) World
Vertical tab — similar Hello (vertical
\v "Hello\vWorld"
to a line break space) World
Bell/alert — triggers a
\a print("\a") (sound)
system alert sound
Octal value —
\ooo character specified by \101 (octal for 'A') A
octal value
Hexadecimal value —
\xhh character specified by \x41 (hex for 'A') A
hexadecimal
13 | P a g e
print("Hello\nWorld")
# Output: # Hello
# World
Lists in Python
A list is a built-in data structure in Python that stores an ordered, changeable, and
mutable collection of elements. It can hold items of different data types, including integers,
strings, and even other lists.
Key Features of Lists:
Ordered: Elements are stored in a specific order, starting from index 0.
Mutable: You can change, add, or remove elements after the list is created.
Duplicates Allowed: Lists can have repeated values.
Creating Lists:
Lists are defined using square brackets [ ] with elements separated by commas.
An empty list can be created with [] or list().
Examples:
14 | P a g e
tuple1 = (1, 2, 3, 4)
list2 = list(tuple1)
print(list2) # Output: [1, 2, 3, 4]
# Modifying a value
fruits[1] = 'blueberry'
print(fruits) # Output: ['apple', 'blueberry', 'cherry']
List Operations:
Append: Add an element to the end. list.append(value)
Insert: Add an element at a specified position. list.insert(index, value)
Remove: Remove the first occurrence of a value. list.remove(value)
Pop: Remove and return the item at a specific index. list.pop(index)
Extend: Add multiple elements from another list. list.extend([values])
Example:
1. Append:
numbers = [1, 2, 3]
numbers.append(4)
print(numbers) # Output: [1, 2, 3, 4]
2. Insert:
numbers.insert(1, 5)
print(numbers) # Output: [1, 5, 2, 3, 4]
3. Remove:
numbers.remove(5)
15 | P a g e
print(numbers) # Output: [1, 2, 3, 4]
4. Pop:
numbers.pop(2)
print(numbers) # Output: [1, 2, 4]
5. Extend:
numbers.extend([6, 7, 8])
print(numbers) # Output: [1, 2, 4, 6, 7, 8]
Variables in Python
Variables are containers used to store data values. They can hold different data types like
integers, floats, strings, etc.
Rules for Variable Names:
1. Must start with a letter (a-z, A-Z) or an underscore (_).
2. Cannot start with a number.
3. Can only contain alphanumeric characters and underscores (a-z, A-Z, 0-9, _).
4. Variable names are case-sensitive (age, Age, and AGE are different).
16 | P a g e
Multiple Assignments:
You can assign the same value to multiple variables.
Assign different values to multiple variables simultaneously.
Example:
# Assigning the same value to multiple variables
a = b = c = 10
print(a, b, c) # Output: 10 10 10
Outputting Variables:
You can output variables using the print() function.
Python variables can change data types dynamically.
Example:
age = 25
name = "Alice"
17 | P a g e
Expressions in Python
An expression is a combination of values, variables, operators, and function calls
that Python can evaluate to produce a result. Expressions are fundamental in programming
and are used for calculations, data processing, and decision-making.
Examples of Expressions:
# Using values directly
result = 10 + 5 # Simple expression with values
print(result) # Output: 15
# Using variables
x = 10
y = 20
sum_value = x + y # Expression with variables
print(sum_value) # Output: 30
Types of Expressions:
1. Arithmetic Expressions: Involves arithmetic operators (+, -, *, /, %).
2. Relational Expressions: Compares values and returns a Boolean (True or False).
18 | P a g e
3. Logical Expressions: Combines multiple conditions using logical operators (and, or,
not).
4. String Expressions: Combines or manipulates strings (+ for concatenation).
x = 10
print(x) # Output: 10
19 | P a g e
2. Relational (Comparison) Operators:
Operator Description Example Result
== Equal to 5 == 5 True
!= Not equal to 5 != 3 True
> Greater than 5>3 True
< Less than 5<3 False
>= Greater than or equal to 5 >= 5 True
<= Less than or equal to 5 <= 3 False
3. Logical Operators:
Operator Description Example Result
4. Bitwise Operators:
Operator Description Example Result
` ` OR `5
^ XOR 5^3 6
Expression Evaluation:
Python follows the PEMDAS (Parentheses, Exponentiation, Multiplication/Division,
and Addition/Subtraction) rule for evaluating expressions.
20 | P a g e
Example:
result = (2 + 3) * 4 ** 2 / 8 - 3
print(result) # Output: 8.0
(2 + 3) → 5
4 ** 2 → 16
5 * 16 → 80
80 / 8 → 10.0
10.0 - 3 → 7.0
Comments in Python
Comments are used to explain the code, make it more readable, and help others
understand the logic. They are not executed by Python.
1. Single-Line Comments:
Output:
Hello, World!
2. Multi-Line Comments:
21 | P a g e
Python doesn't have a specific syntax for multi-line comments like other languages. Instead,
you can use:
Multiple single-line comments with #
Triple quotes (""" """ or ''' ''') for block comments or documentation strings.
'''
This is also a multi-line comment
using triple single quotes.
'''
print("Using triple single quotes for comments")
Output:
Multiple single-line comments
Using triple double quotes for comments
Using triple single quotes for comments
22 | P a g e
Triple quotes (""" """) are primarily used for docstrings—a way to document
functions, classes, and modules.
If used outside of these, they act like multi-line comments.
Example of Docstrings:
def greet():
"""
This function greets the user.
It uses a simple print statement.
"""
print("Hello, User!")
greet()
Modules in Python
A module in Python is a file containing Python definitions and statements—like
functions, classes, and variables—saved with a .py extension. It helps organize code
logically, making it reusable and maintainable.
Why Use Modules?
Code Organization: Divide large programs into smaller, manageable files.
Reusability: Use pre-defined functions and variables from existing modules.
Namespace Management: Avoid conflicts by isolating function and variable names.
Built-in Functions: Access powerful built-in modules like math, sys, os, etc.
Creating a Module
You can create a Python module by saving a Python file with a .py extension.
Example:
Create a file named mymodule.py with the following code:
# mymodule.py
def greet(name):
return f"Hello, {name}!"
pi = 3.1416
23 | P a g e
Using a Module:
To use a module, use the import keyword.
Syntax:
import <module_name>
Example:
import mymodule
Built-in Modules:
Python provides a wide range of built-in modules. You can explore them using the
help() function.
Example of Built-in Modules:
import sys
print(sys.version) # Displays Python version
24 | P a g e
import calendar
print(calendar.month(2021, 5)) # Prints the calendar for March 2021
True
False
import random
print(random.randint(1, 10)) # Generates a random number between 1 and 10
25 | P a g e
help(math.sqrt) # Details about the sqrt function
Functions in Python
A function is a block of organized, reusable code that performs a specific task.
Functions help to divide a large program into smaller, manageable, and modular chunks,
enhancing code readability, reusability, and maintainability.
Types of Functions:
1. Built-in Functions: Predefined in Python, like print(), abs(), len(), etc.
2. User-defined Functions: Created by the user to perform specific tasks.
1. Built-in Functions:
Python has numerous built-in functions available for use.
Examples:
# Using abs() to get absolute value
integer = -20
print("Absolute value of -20 is:", abs(integer)) # Output: Absolute value of -20 is: 20
2. User-defined Functions:
Users can define their own functions using the def keyword.
Syntax:
def function_name(parameters):
# Code block
return value # Optional
Example:
26 | P a g e
def add_numbers(x, y):
sum = x + y
return sum
Calling a Function:
To execute a function, you need to "call" it. The function name followed by
parentheses () triggers the function.
Example:
def greet(name):
return f"Hello, {name}!"
Flow of Execution:
1. Execution begins from the first line of the program.
2. Statements are executed one by one, from top to bottom.
3. When a function is defined, Python skips the function body until the function is
called.
4. When a function is called, Python jumps to its definition, executes it, and returns to
where it was called.
Example of Flow:
def say_hello():
print("Hello, World!")
27 | P a g e
print("After function call")
Output:
Before function call
Hello, World!
After function call
Default Parameters:
You can assign default values to parameters.
Example:
def greet(name="Guest"):
print(f"Hello, {name}!")
a, b, c = get_values()
print(a, b, c) # Output: 10 20 30
28 | P a g e
Variable Scope:
Local Scope: Variables inside a function.
Global Scope: Variables outside any function.
Example:
x = 10 # Global variable
def display():
x = 5 # Local variable
print("Inside function:", x)
Lambda Functions:
Anonymous functions defined using the lambda keyword.
Syntax:
lambda arguments: expression
Example:
double = lambda x: x * 2
print(double(5)) # Output: 10
What is Recursion?
Recursion is a method where a function calls itself to solve a problem. It breaks down
a complex problem into smaller, more manageable problems until it reaches a base condition
that stops the recursion.
29 | P a g e
Key Components of Recursion:
1. Base Case: The condition that stops the recursion, preventing an infinite loop.
2. Recursive Call: The function calling itself to work towards the base case.
Explanation:
When n == 0, the function stops recursion (base case).
Otherwise, the function keeps calling itself with n-1.
Disadvantages of Recursion:
May lead to high memory usage due to the call stack.
Can result in a stack overflow if the base case is not defined correctly.
Often slower than iterative solutions due to multiple function calls.
1. Conditional Statements
31 | P a g e
print("Continue")
b. Nested if-else
Using an if statement inside another if statement.
Syntax:
if condition1:
if condition2:
# Block 1
else:
# Block 2
else:
# Block 3
Example:
x = 10
y = 20
if x < 15:
if y < 25:
print("Both conditions are True")
else:
print("Second condition is False")
else:
print("First condition is False")
c. elif Statement
Used to check multiple conditions.
Syntax:
if condition1:
# Block 1
elif condition2:
# Block 2
else:
32 | P a g e
# Block 3
Example:
marks = 85
if marks >= 90:
print("Grade: A")
elif marks >= 75:
print("Grade: B")
else:
print("Grade: C")
2. Looping Statements
Looping statements repeatedly execute a block of code until a condition becomes
False.
a. while Loop
Executes a block of code as long as the condition is True.
Syntax:
while condition:
# Code block
Example:
counter = 0
while counter < 5:
print("Counter:", counter)
counter += 1
b. for Loop
Used to iterate over a sequence (like a list, tuple, string).
Syntax:
for variable in sequence:
# Code block
33 | P a g e
print("Squares:", squares)
c. Nested Loops
A loop inside another loop.
Example:
for i in range(3):
for j in range(2):
print(f"i={i}, j={j}")
while i <= n:
if i % 2 == 0:
print("Even number:", i)
i += 2
while i <= n:
if i % 2 == 0:
print(f"Square of {i} is", i ** 2)
i += 2
34 | P a g e
d. Print squares of even numbers using for loop:
n = int(input("Enter the value of n: "))
1. Break Statement
The break statement is used to terminate the loop immediately when a specific
condition is met.
If the break is inside a nested loop, it terminates only the innermost loop.
Syntax:
for var in sequence:
if condition:
break
# Code block
35 | P a g e
while condition:
if condition:
break
# Code block
36 | P a g e
The number 88 is found. Terminating the loop.
2. Continue Statement
The continue statement skips the rest of the code inside the loop for the current
iteration and moves to the next iteration.
It is used to skip certain conditions without terminating the loop.
Syntax:
for var in sequence:
if condition:
continue
# Code block
while condition:
if condition:
continue
# Code block
37 | P a g e
if num % 2 == 0:
continue
print(num)
Output:
11
9
89
3. Pass Statement
The pass statement is a null operation — it does nothing.
It is used as a placeholder where code is syntactically required but not yet
implemented.
Syntax:
for val in sequence:
pass
def function_name():
pass
38 | P a g e
class MyClass:
pass
Example:
sequence = {'p', 'a', 's', 's'}
for val in sequence:
pass # Placeholder for future code
class MyClass:
pass # Class with no methods or properties yet
String Module
The string module contains functions to process standard Python strings. It must be
imported before use.
Syntax:
import string
Example:
import string
print("All letters:", string.ascii_letters)
print("Lowercase letters:", string.ascii_lowercase)
print("Uppercase letters:", string.ascii_uppercase)
print("Digits:", string.digits)
print("Hexadecimal digits:", string.hexdigits)
print("Whitespace characters:", string.whitespace)
print("Punctuation marks:", string.punctuation)
Output:
All letters: abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ
39 | P a g e
Lowercase letters: abcdefghijklmnopqrstuvwxyz
Uppercase letters: ABCDEFGHIJKLMNOPQRSTUVWXYZ
Digits: 0123456789
Hexadecimal digits: 0123456789abcdefABCDEF
Whitespace characters:
\r
Python Arrays
Introduction
An array is a container that can hold a fixed number of items, all of the same data
type.
Arrays are used for storing multiple values in a single variable.
In Python, arrays are available via the array module.
Key Concepts:
Element: An individual item stored in an array.
Index: The numerical position used to identify each element in an array.
Indexing starts from 0.
Array Representation
Example:
Int array[10] = {10, 20, 30, 40, 50, 60, 70, 80, 85, 90}
Index: 0 1 2 3 4 5 6 7 8 9
Array length = 10
Access element 70 using index 6.
40 | P a g e
Creating an Array in Python
from array import *
array_name = array(typecode, [initializers])
Common Typecodes:
c Character (1 byte)
Output:
10
20
30
40
50
41 | P a g e
Accessing Array Elements
from array import *
arr = array('i', [10, 20, 30, 40, 50])
Output:
10
30
Array Methods
Method Description
append() Adds an element to the end of the array
clear() Removes all elements
copy() Returns a copy of the array
count() Counts occurrences of a specified value
extend() Extends the array by appending elements
index() Returns the index of the first occurrence
insert() Adds an element at a specified position
pop() Removes the element at a specified position
remove() Removes the first occurrence of a specified value
reverse() Reverses the order of elements
sort() Sorts the elements (for lists, not arrays)
arr.append(60)
print("After append:", arr)
42 | P a g e
arr.remove(30)
print("After remove:", arr)
arr.insert(2, 25)
print("After insert:", arr)
arr.pop(1)
print("After pop:", arr)
arr.reverse()
print("After reverse:", arr)
Output:
After append: array('i', [10, 20, 30, 40, 50, 60])
After remove: array('i', [10, 20, 40, 50, 60])
After insert: array('i', [10, 20, 25, 40, 50, 60])
After pop: array('i', [10, 25, 40, 50, 60])
Index of 40: 2
After reverse: array('i', [60, 50, 40, 25, 10])
43 | P a g e
Length: len(list1) returns the number of elements.
Concatenation: [1, 2] + [3, 4] results in [1, 2, 3, 4].
Repetition: ['Hi!'] * 4 results in ['Hi!', 'Hi!', 'Hi!', 'Hi!'].
Membership Test: 3 in [1, 2, 3] returns True.
Cloning Lists:
To create a copy (clone) of a list, use slicing or the list() constructor:
x = list1[:] # Cloning using slicing
y = list(list1) # Cloning using list()
List Comprehension:
A concise way to create lists:
squares = [x**2 for x in range(10)] # Output: [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
Tuples
A tuple is an ordered and immutable collection. Tuples can contain multiple data
types and are defined using parentheses.
44 | P a g e
Creating Tuples:
tuple1 = (1, 2, 3, 4)
empty_tuple = () # Empty tuple
single_element_tuple = (1,) # Single element tuple
Dictionaries
A dictionary is an unordered, mutable collection that stores key-value pairs. They are
defined with curly braces.
Creating Dictionaries:
dict1 = {"brand": "TECHIN IT", "model": "college", "year": 2004}
Dictionary Operations:
Access values using keys: dict1["brand"] returns "TECHIN IT".
Adding new key-value pairs: dict1["location"] = "city".
Removing items: del dict1["year"].
Dictionary Comprehension:
A concise way to create dictionaries:
squared_dict = {x: x**2 for x in range(5)} # Output: {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}
Encapsulation:
This principle restricts direct access to some of an object's components and can
prevent the accidental modification of data. It is achieved using private and public access
modifiers.
Example:
class BankAccount:
def __init__(self, balance=0):
self.__balance = balance # Private attribute
46 | P a g e
self.__balance += amount
def get_balance(self):
return self.__balance
account = BankAccount()
account.deposit(100)
print(account.get_balance()) # Output: 100
Inheritance:
Inheritance allows a new class (child or subclass) to inherit attributes and methods
from an existing class (parent or superclass). This promotes code reusability.
Example:
class Animal:
def speak(self):
return "Animal speaks"
class Cat(Animal): # Cat inherits from Animal
def speak(self):
return "Meow"
my_cat = Cat()
print(my_cat.speak()) # Output: Meow
Types of Inheritance
Inheritance in Object-Oriented Programming (OOP) allows a class (subclass or derived
class) to inherit attributes and methods from another class (superclass or base class). This
promotes code reusability and establishes a relationship between classes. Here are the main
Types of inheritance:
47 | P a g e
1. Single Inheritance:
A subclass inherits from only one superclass.
Example:
class Animal:
def speak(self):
return "Animal speaks"
class Dog(Animal): # Single Inheritance
def bark(self):
return "Woof!"
dog = Dog()
print(dog.speak()) # Output: Animal speaks
2. Multiple Inheritance:
A subclass inherits from multiple superclasses. This can lead to complexity but allows
for more versatile class designs.
Example:
class Canine:
def bark(self):
return "Woof!"
48 | P a g e
class Feline:
def meow(self):
return "Meow!"
class Cat(Canine, Feline): # Multiple Inheritance
pass
cat = Cat()
print(cat.bark()) # Output: Woof!
print(cat.meow()) # Output: Meow!
3. Multilevel Inheritance:
A subclass inherits from a superclass, which itself is a subclass of another superclass.
Example:
class Animal:
def speak(self):
return "Animal speaks"
class Dog(Animal): # Inherits from Animal
def bark(self):
return "Woof!"
class Puppy(Dog): # Inherits from Dog
def cry(self):
return "Whimper!"
puppy = Puppy()
print(puppy.speak()) # Output: Animal speaks
4. Hierarchical Inheritance:
Multiple subclasses inherit from a single superclass.
Example:
class Vehicle:
def start(self):
return "Starting vehicle"
49 | P a g e
class Car(Vehicle): # Inherits from Vehicle
def drive(self):
return "Driving car"
class Bike(Vehicle): # Inherits from Vehicle
def ride(self):
return "Riding bike"
car = Car()
bike = Bike()
print(car.start()) # Output: Starting vehicle
print(bike.start()) # Output: Starting vehicle
Example:
class A:
def method_a(self):
return "Method A"
class B(A):
def method_b(self):
return "Method B"
class C(A):
def method_c(self):
return "Method C"
class D(B, C): # Hybrid Inheritance
def method_d(self):
return "Method D"
obj = D()
print(obj.method_a()) # Output: Method A
50 | P a g e
Method overloading allows a class to have multiple methods with the same name but
different parameters (number or type). It is primarily used to provide flexibility in method
functionality.
Note: Python does not support method overloading in the traditional sense as seen in
languages like Java or C++. Instead, you can achieve similar behavior using default
arguments or variable-length arguments.
Example:
class MathOperations:
def add(self, a, b, c=0): # Default argument
return a + b + c
math = MathOperations()
print(math.add(1, 2)) # Output: 3
print(math.add(1, 2, 3)) # Output: 6
Method Overriding
Method overriding occurs when a subclass provides a specific implementation of a
method that is already defined in its superclass. The overridden method in the subclass should
have the same name, return type, and parameters as the method in the superclass.
51 | P a g e
Example:
class Animal:
def speak(self):
return "Animal speaks"
class Dog(Animal):
def speak(self): # Overriding the speak method
return "Woof!"
dog = Dog()
print(dog.speak()) # Output: Woof!
Polymorphism:
Polymorphism allows methods to do different things based on the object that it is
acting upon, typically through method overriding or interfaces.
Example:
class Bird:
def fly(self):
return "Flies high"
class Penguin(Bird):
def fly(self):
return "Cannot fly"
birds = [Bird(), Penguin()]
for bird in birds:
print(bird.fly()) # Output: Flies high, Cannot fly
52 | P a g e
Abstraction:
Abstraction is the concept of hiding the complex reality while exposing only the
necessary parts. It can be achieved using abstract classes and interfaces.
Example:
from abc import ABC, abstractmethod
class Shape(ABC):
@abstractmethod
def area(self):
pass
class Rectangle(Shape):
def __init__(self, width, height):
self.width = width
self.height = height
def area(self):
return self.width * self.height
rect = Rectangle(5, 10)
print(rect.area()) # Output: 50
Benefits of OOP
Modularity: Code is organized into discrete classes, making it easier to manage and
understand.
Reusability: Classes can be reused across different programs, reducing redundancy.
Scalability: OOP makes it easier to scale applications by allowing for the addition of
new classes without affecting existing code.
Maintainability: Changes made in one part of the code can be localized to specific
classes, making maintenance easier.
Python Modules and Packages
Python modules and packages are essential components for organizing and structuring
code, particularly as programs grow in complexity. They help separate functionality into
manageable sections, making the code easier to maintain and reuse.
What is a Module?
53 | P a g e
A module is a file containing Python code that can define functions, classes, and
variables. It allows you to encapsulate code into separate files, which can be reused across
different programs or scripts.
Example of a Module: addition.py
# addition.py
def add(a, b):
result = a + b
return result
This module defines a function add() that takes two numbers and returns their sum.
Importing Modules
You can import a module into another module or an interactive Python session using
the import statement.
Output:
The value of pi is 3.141592653589793
54 | P a g e
print(m.pi) # Output: 3.141592653589793
Output:
2022-12-27 08:26:49.219717
55 | P a g e
print(current_date)
Output:
2022-12-27
Output:
['MAXYEAR', 'MINYEAR', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__',
'__name__', '__package__', '__spec__', 'date', 'datetime', 'time', 'timedelta', 'timezone', 'tzinfo']
todays_date = date.today()
print("Today's date =", todays_date)
Output:
Today's date = 2022-12-27
56 | P a g e
Getting Year, Month, and Day
today = date.today()
print("Current year:", today.year)
print("Current month:", today.month)
print("Current day:", today.day)
Output:
Current year: 2022
Current month: 12
Current day: 27
57 | P a g e
Example: Checking a String Pattern
You can check if a string starts with "The" and ends with "Spain":
txt = "The rain in Spain"
x = re.search("^The.*Spain$", txt)
if x:
print("Match found!")
else:
print("No match.")
FUNCTION DESCRIPTION
split Returns a list where the string has been split at each match
58 | P a g e
print(split_txt) # Output: ['The', 'rain', 'in', 'Spain']
Metacharacters in RegEx
Metacharacters are characters that have special meanings in regular expressions. Here
are some common metacharacters:
Output:
Search successful.
59 | P a g e
In this example, the pattern ^a...s$ checks if the string starts with 'a', followed by any
three characters, and ends with 's'.
Python pip
What is pip?
pip is the standard package manager for Python, allowing users to install and manage
additional packages that are not included in the Python standard library. With pip, you can
easily download libraries and frameworks from the Python Package Index (PyPI) and
integrate them into your projects.
Example: To install the NumPy library, you would use the following command:
pip install numpy
Using pip
pip is a command-line program that can be used through the terminal or command prompt.
The basic syntax for using pip is:
pip <pip arguments>
Installing Packages with pip
The primary function of pip is to install packages. Most packages are hosted on the Python
Package Index (PyPI), which contains a vast collection of libraries contributed by the Python
community.
Basic Package Installation:
To install a package, you use the install command followed by the package name. For
example, to install the requests library, you would run:
pip install requests
60 | P a g e
Listing Installed Packages with pip
You can list all the packages currently installed in your Python environment using the
following command:
pip list
Sample Output:
Package Version
---------- ----------
certifi 2019.11.28
chardet 3.0.4
idna 2.8
pip 19.3.1
requests 2.22.0
setuptools 45.0.0
urllib3 1.25.7
wheel 0.33.6
This output displays the names and versions of all installed packages, helping you
keep track of your dependencies.
61 | P a g e
Example: Handling Division by Zero
try:
numerator = 10
denominator = 0
result = numerator / denominator
print(result)
except:
print("Error: Denominator cannot be 0.")
Output:
Error: Denominator cannot be 0.
In this example, attempting to divide by zero raises an exception. The code inside
the try block is skipped, and the except block executes.
62 | P a g e
print(result)
except:
print("Error: Denominator cannot be 0.")
finally:
print("This is the finally block.")
Output:
Error: Denominator cannot be 0.
This is the finally block.
File Modes:
Mode Description
r Open a file for reading (default).
w Open a file for writing; creates a new file or truncates an existing file.
x Open a file for exclusive creation; fails if the file exists.
a Open a file for appending; creates a new file if it does not exist.
t Open in text mode (default).
b Open in binary mode.
+ Open a file for updating (reading and writing).
63 | P a g e
file1 = open("test.txt") # equivalent to 'r' or 'rt'
file1 = open("test.txt", 'w') # write in text mode
file1 = open("img.bmp", 'r+b') # read and write in binary mode
Reading Files in Python
Once a file is opened, you can read its contents using methods like read(), readline(),
or readlines().
Example: Reading a File
# Open a file for reading
file1 = open("test.txt", "r")
# Read the file
read_content = file1.read()
print(read_content)
# Don't forget to close the file
file1.close()
Sample Output:
This is a test file.
Hello from the test file.
HANDS ON PROJECT
import speech_recognition as sr
import wikipedia
import webbrowser
import os
# init pyttsx
engine = pyttsx3.init("sapi5")
voices = engine.getProperty("voices")
def speak(audio):
engine.say(audio)
engine.runAndWait()
def take_command():
r = sr.Recognizer()
print("Listening...")
r.pause_threshold = 1
audio = r.listen(source)
try:
print("Recognizing...")
except Exception as e:
65 | P a g e
print(e)
return "None"
return query
if __name__ == '__main__':
speak("HI WELCOME")
while True:
query = take_command().lower()
if 'wikipedia' in query:
speak("According to wikipedia")
speak(results)
speak("opening youtube")
webbrowser.open("youtube.com")
speak("opening google")
webbrowser.open("google.com")
speak("opening github")
webbrowser.open("github.com")
speak("opening stackoverflow")
webbrowser.open("stackoverflow.com")
66 | P a g e
elif 'open spotify' in query:
speak("opening spotify")
webbrowser.open("spotify.com")
speak("opening whatsapp")
loc = "C:\\Users\\jaspr\\AppData\\Local\\WhatsApp\\
WhatsApp.exe"
os.startfile(loc)
speak("opening music")
webbrowser.open("spotify.com")
speak("opening music")
webbrowser.open("spotify.com")
webbrowser.open("D://")
webbrowser.open("C://")
webbrowser.open("E://")
exit(0)
SCREEN SHOTS:
67 | P a g e
68 | P a g e