0% found this document useful (0 votes)
5 views71 pages

ADITYA DOCUMENT Voice Assistant

This project report details the industrial training undertaken by Dolanki Rohit Lalitha Kishore at Techin IT, Hyderabad, as part of the Diploma in Computer Engineering program at Aditya College of Engineering & Technology. The report includes an overview of Python programming, its features, and various data types, alongside a structured index of topics covered. Acknowledgments are given to faculty and staff for their support during the training period.

Uploaded by

rohitbunny2006
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views71 pages

ADITYA DOCUMENT Voice Assistant

This project report details the industrial training undertaken by Dolanki Rohit Lalitha Kishore at Techin IT, Hyderabad, as part of the Diploma in Computer Engineering program at Aditya College of Engineering & Technology. The report includes an overview of Python programming, its features, and various data types, alongside a structured index of topics covered. Acknowledgments are given to faculty and staff for their support during the training period.

Uploaded by

rohitbunny2006
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 71

A PROJECT REPORT ON INDUSTRIAL TRAINING

Submitted in partial fulfilment of the requirements for the award of

DIPLOMA IN

COMPUTER ENGINEERING

Submitted By

Name: Dolanki Rohit Lalitha kishore


Pin no: - Pin no : 22404-cm-033
Academic Year 2024-2025

DEPARTMENT OF COMPUTER ENGINEERING

ADITYA COLLEGE OF ENGINEERING &


TECHNOLOGY
(POLYTECHNIC -255)
SURAMPALEM - 533 437 (2024-2025)

i|Page
ADITYA COLLEGE OF ENGINEERING &
TECHNOLOGY
(POLYTECHNIC -249)
SURAMPALEM
DEPARTMENT OF COMPUTER ENGINEERING

CERTIFICATE

This is to certify that this project work entitled

“____________________________________________” is the bonafied work of

PIN.NO……………………………… Mr/Miss………..……….....……….…….…………. of

final year DCME branch along with his/her batch mates submitted in partial fulfilment of the

requirements for the award of DIPLOMA IN COMPUTER ENGINEERING of State Board

of Technical Education & Training, T.S., Hyderabad during the academic year 2024-2025.

Training Supervisor Training Mentor HOD

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.

Thank you all.

- D. Rohit Lalitha Kishore

iii | P a g e
ABSTRACT

"Techin IT Process Private Limited is a company incorporated under


the companies Act 2013. Techin IT process governs many constraints in the arena
of education and employment. With the aspect of providing qualified service to the
clients and students, the company mainly focusses on 1. Admission process 2.
Internships 3. Industrial trainings 4. Campus trainings 5. Campus placements 6.
Professional courses training and placements 7. Career Guidance 8. Educational
loan process 9. Payroll services 10. HR Consulting 11. Contractual Staffing 12.
Recruitment process 13. Training and Development"

Techin IT process private limited is a company that provides the


courses such as java, core java, .net, python, python full stack, java full stack, AWS,
power BI, azure, data structure, big data, tally, business accounts, GST, SAP (FICO,
MM) HRM, HR payroll management, software IT development, advance IT
software training.

It provides services like software development, web designing,


app development, digital marketing, payroll process, recruitment, campus
recruitment. This company has been found in compliance with requirements of
quality management system ISO 9001:2015.

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.

Why Learn Python?


 Easy to Learn: Python’s syntax is straightforward, resembling everyday English.
 Versatile: Used in various fields — web development, data analysis, AI, machine
learning, automation, etc.
 Extensive Libraries: Python has rich libraries like NumPy, Pandas, TensorFlow, and
Django.
 Strong Community: A large community for support and resources.
 High Demand: Python developers are in high demand in the tech industry.

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.

Getting Started with Python Programming:


Finding an Interpreter:
To run Python code, you need a Python interpreter. This can be done through:
1. Online Interpreters: If you don’t want to install Python immediately, you can use
these online interpreters:
o GeeksforGeeks IDE
o Ideone
o Codepad

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.

2. Download the latest Python 3 version.


3. Open the installer and check the box “Add Python to PATH” before installing.
4. Follow the instructions to complete the installation.

To check if installed correctly:


Open Command Prompt and type:
python --version
This should display the installed Python version.
For macOS:
 Python 2 comes pre-installed. However, you should install Python 3.
 Use Homebrew (if installed) to install Python:
brew install python3
 Alternatively, download Python from python.org.
For Linux:
 Most Linux distributions come with Python pre-installed.
 To install Python 3, use the terminal:
sudo apt update

4|Page
sudo apt install python3

Running Python Programs:


Using IDLE (Integrated Development and Learning Environment):
 IDLE is installed automatically with Python.
 Open IDLE, write your Python code, and click Run.
Using Command Prompt/Terminal:
 Open Command Prompt (Windows) or Terminal (macOS/Linux).
 Type python or python3 to enter the Python interpreter.
 Type code directly or run a Python script saved with a .py extension:
python filename.py

Using a Code Editor (like VS Code):


1. Install VS Code.
2. Install the Python extension from the VS Code Marketplace.
3. Open a Python file (.py), write code, and run it using the Run button or terminal.

Why Use Python?


Python is a popular and powerful programming language widely used in various fields
like web development, data analysis, machine learning, AI, automation, and more. It has
several features that make it a preferred choice for both beginners and experienced
developers.
Key Features of Python:
1. Object-Oriented Programming (OOP):
 Python supports object-oriented programming, including essential OOP concepts like
polymorphism, inheritance, encapsulation, and method overloading.
 This makes it easy to create and manage complex applications.

2. Easy to Learn and Use:


 Python's syntax resembles plain English, making it beginner-friendly.
 It emphasizes readability and reduces the cost of program maintenance.
 Its simple structure allows developers to write programs quickly and efficiently.

3. Free and Open Source:

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

5. Extensive Standard Library:


 Python comes with a rich standard library that covers a wide range of functionalities
— file handling, internet protocols, web services, data processing, and more.
 Additionally, there are powerful third-party libraries like:
o NumPy for numerical calculations
o SciPy for scientific computing
o Pandas for data analysis
o Matplotlib for data visualization
o Django/Flask for web development

6. Automatic Memory Management:


 Python has an automatic garbage collector to handle memory management.
 This reduces the need for manual memory allocation and prevents memory leaks.

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.

10. Straightforward Syntax:


 Python’s syntax is clean and straightforward, reducing the complexity of code.
 It relies on indentation to define code blocks instead of braces {}, making the code
more readable.
Example:
def greet(name):
print(f"Hello, {name}!") # Indentation defines code blocks

greet("Alice")

11. High Development Speed:


 Python’s interpreted nature and byte code compilation combine the development
speed of scripting languages with the performance benefits of compiled languages.

Working with Python — Python Code Execution


How Python Code is executed:
Python follows a traditional runtime execution model where your source code is
translated to byte code before being executed by the Python Virtual Machine (PVM).

Stages of Python Code Execution:


1. Source Code (.py): The original code written by the developer.
2. Byte Code (.pyc): Python automatically compiles the source code to byte code. Byte
code is a lower-level, platform-independent representation of your source code.
3. Python Virtual Machine (PVM): The PVM interprets the byte code and executes it.
Note: This compilation to byte code happens internally. You don't need to manually compile
your Python code.

7|Page
Python Execution Flow:

PVM
m.pyc
m.py

 Source code extension is .py


 Byte code extension is .pyc (Compiled python code)

Modes of Running Python Programs:


Python can be executed in two primary ways:
1. Interactive Mode:
 In interactive mode, you use the Python interpreter to execute code line by line.
 This mode is helpful for quick testing, experimenting, and learning.
How to Enter Interactive Mode:
1. Open your Command Prompt (Windows) or Terminal (macOS/Linux).
2. Type python or python3 (depending on your installation) and press Enter.
3. You will see the >>> symbol, known as the prompt, indicating that the interpreter is
ready.
Example:
>>>print("Hello, World!")
Hello, World!

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

Comparison Between Interactive Mode and Script Mode:


Feature Interactive Mode Script Mode
Execution Style Line-by-line, immediate feedback Executes the whole script at once
Use Case Quick testing, learning Writing complex programs
File No need for a file Requires a .py file
Requirement
Error Handling Immediate error feedback Errors found after running script
Flexibility High for experimentation High for development and projects

Python Data Types


Data types define the kind of value a variable can hold in Python. Each data type has
specific properties and behaviors.
Python has several standard data types that are used to store various types of data. These
include:
1. Integer (int)
2. Floating Point (float)

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

# Checking the data type


print(type(a)) # Output: <class 'int'>

2. Floating Point (float):


 Floats are numbers that contain a decimal point or are written in exponential
(scientific) notation.
 They can represent both positive and negative numbers.
Examples:
x = 2.8
y = -4.5
z = 1.2e3 # Scientific notation (1.2 * 10^3)
print(x) # Output: 2.8
print(y) # Output: -4.5
print(z) # Output: 1200.0

# Checking the data type


print(type(x)) # Output: <class 'float'>

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

# Checking the data type


print(type(a)) # Output: <class 'bool'>

Boolean as a result of comparison:


print(5 > 3) # Output: True
print(5 < 3) # 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

# Checking the data type


print(type(name)) # Output: <class 'str'>

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:

Data Type Description Example


int Whole numbers (positive/negative) 5, -10, 0
float Decimal or scientific notation 3.14, 2.5e3
bool Logical values: True or False True, False
str Sequence of characters (strings) "Hello", '123'

Escape Sequences in Python


An escape sequence is a combination of a backslash (\) followed by a character that
has a special meaning in Python.
Escape sequences are used to:
 Insert characters that are not easily typed on the keyboard.
 Include special characters like quotes within a string.
 Control formatting within a string, such as creating a new line or a tab space.

Common Escape Sequences and Their Interpretations:


Escape Sequence Meaning Example Output
Literal single quote (')
\' 'It\'s Python!' It's Python!
inside a string

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

Examples of Escape Sequences in Use:

1. Single and Double Quotes:

print('It\'s a beautiful day!') # Output: It's a beautiful day!


print("She said, \"Hello!\"") # Output: She said, "Hello!"

2. Backslash and Newline:

print("C:\\Users\\Documents") # Output: C:\Users\Documents

13 | P a g e
print("Hello\nWorld")
# Output: # Hello
# World

3. Tab and Backspace:

print("Name:\tAlice") # Output: Name: Alice


print("Oops\b!") # Output: Oops!

4. Carriage Return (\r):

print("Hello\rWorld") # Output: World

The text "Hello" is overwritten by "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:

# Creating a list with mixed data types


list1 = [1, 2, 3, 'A', 'B', 7, 8, [10, 11]]
print(list1) # Output: [1, 2, 3, 'A', 'B', 7, 8, [10, 11]]

# Creating an empty list


empty_list = []
print(empty_list) # Output: []

# Using the list() constructor to create a list from a tuple

14 | P a g e
tuple1 = (1, 2, 3, 4)
list2 = list(tuple1)
print(list2) # Output: [1, 2, 3, 4]

Accessing and Modifying List Elements:


 Access elements using indexing (list[index]).
 Lists are zero-indexed, meaning the first element is at index 0.
 You can use negative indexing to access elements from the end (-1 for the last item).
Example:
fruits = ['apple', 'banana', 'cherry']
print(fruits[0]) # Output: apple
print(fruits[-1]) # Output: cherry

# 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).

Assigning Values to Variables:


 Python does not require declaring variables with a specific data type.
 The data type is determined automatically when a value is assigned.
Example:
x = 100 # Integer
y = 1000.5 # Float
name = "John" # String

print(x, y, name) # Output: 100 1000.5 John


print(type(x)) # Output: <class 'int'>
print(type(y)) # Output: <class 'float'>
print(type(name)) # Output: <class 'str'>

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

# Assigning different values to multiple variables


x, y, z = 1, 2, "TECHIN IT"
print(x, y, z) # Output: 1 2 TECHIN IT

Outputting Variables:
 You can output variables using the print() function.
 Python variables can change data types dynamically.
Example:
age = 25
name = "Alice"

print("Name:", name) # Output: Name: Alice


print("Age:", age) # Output: Age: 25

# Changing the data type


age = "Twenty-five"
print("Updated Age:", age) # Output: Updated Age: Twenty-five

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.

Key Components of Expressions:


1. Values: Constants or literals like numbers (10, 3.14) or strings ("Hello").
2. Variables: Named references to stored data (x, name).
3. Operators: Symbols that perform operations on variables and values (+, -, *, etc.).

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

# Mixing values and variables


a=7
b=3
expr = a * 2 + b - 4
print(expr) # Output: 13

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

Simple vs. Complex Expressions:


 Simple Expression: Consists of a single value or variable.

x = 10
print(x) # Output: 10

 Complex Expression: Contains multiple operators and variables.


x=5
y = 10
result = (x + y) * 2 - 5
print(result) # Output: 25

Identifiers, Literals, and Operators:


 Identifiers: Names used for variables, functions, classes, etc. (name, age, total).
 Literals: Fixed values like numbers (10, 3.14), strings ("Hello"), booleans (True,
False).
 Operators: Symbols used to perform operations.
Operators in Python:
Python provides a variety of operators to perform different operations:
1. Arithmetic Operators:
Operator Description Example Result
+ Addition 5+2 7
- Subtraction 5-2 3
* Multiplication 5*2 10
/ Division 5/2 2.5
% Modulus 5%2 1
// Floor Division 5 // 2 2
** Exponentiation 5 ** 2 25

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

and Both true (5 > 3) and (3 < 4) True

or One true (5 < 3) or (3 < 4) True

not Reverse not (5 > 3) False

4. Bitwise Operators:
Operator Description Example Result

& AND 5&3 1

` ` OR `5

^ XOR 5^3 6

<< Left shift 5 << 1 10

>> Right shift 5 >> 1 2

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:

 Begin with a hash (#) symbol.


 Everything after the # on that line is considered a comment and ignored by Python.
Example:
# This is a single-line comment
print("Hello, World!") # This prints Hello, World!

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.

Method 1: Using Multiple Single-Line Comments (#):


# This is a comment
# that spans multiple lines
# using multiple hash symbols
print("Multiple single-line comments")

Method 2: Using Triple Quotes (""" """ or ''' '''):


 Triple quotes are technically docstrings, but they can be used as comments when not
associated with functions or classes.
"""
This is a multi-line comment
using triple double quotes.
"""
print("Using triple double quotes for comments")

'''
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

Docstrings vs. Multi-Line 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

print(mymodule.greet("Alice")) # Output: Hello, Alice!


print(mymodule.pi) # Output: 3.1416

Importing Specific Components


You can import specific functions, classes, or variables from a module using from...import.
Example:
from mymodule import greet, pi

print(greet("Bob")) # Output: Hello, Bob!


print(pi) # Output: 3.1416

Renaming a Module with as:


import mymodule as mm
print(mm.greet("Charlie")) # Output: Hello, Charlie!

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

print(calendar.isleap(2024)) # Checks if 2024 is a leap year


print(calendar.isleap(2017)) # Checks if 2017 is a leap year
Output:

True
False

Useful Built-in Modules:


 math: Mathematical functions.
 random: Generate random values.
 datetime: Work with dates and times.
 os: Operating system operations.
 sys: System-specific parameters and functions.
Example:
import math
print(math.sqrt(16)) # Output: 4.0

import random
print(random.randint(1, 10)) # Generates a random number between 1 and 10

Using the help() Function:


 To get information about a module, function, or topic:

help('modules') # List all available modules


help(math) # Detailed information about the math module

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

# Using len() to find the length of a string


name = "Python"
print("Length of the string 'Python' is:", len(name)) # Output: Length of the string 'Python' is:
6

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

result = add_numbers(5, 20)


print("The sum is", result) # Output: The sum is 25
Function Components:
 Function Header: Includes the keyword def, function name, and parameters.
 Docstring (Optional): Describes the function’s purpose.
 Function Body: Block of statements.
 Return Statement: Sends back a value (optional).

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

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

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

print("Before function call")


say_hello() # Function call

27 | P a g e
print("After function call")
Output:
Before function call
Hello, World!
After function call

Parameters and Arguments:


 Parameters: Variables defined in the function definition.
 Arguments: Values passed during the function call.
Example:
def greet(name, age):
print(f"Hello {name}, you are {age} years old.")

greet("Bob", 25) # 'Bob' and 25 are arguments

Default Parameters:
You can assign default values to parameters.
Example:
def greet(name="Guest"):
print(f"Hello, {name}!")

greet() # Output: Hello, Guest!


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

Returning Multiple Values:


A function can return multiple values using a tuple.
Example:
def get_values():
return 10, 20, 30

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)

display() # Output: Inside function: 5


print("Outside function:", x) # Output: Outside function: 10

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.

Example of a Recursive Function (Factorial):


def factorial(n):
if n == 0: # Base case
return 1
else:
return n * factorial(n - 1) # Recursive call

print(factorial(5)) # Output: 120

Explanation:
 When n == 0, the function stops recursion (base case).
 Otherwise, the function keeps calling itself with n-1.

Advantages & Disadvantages of Recursion:


Advantages of Recursion:
 Makes the code cleaner and easier to understand for problems like factorials,
Fibonacci sequences, etc.
 Solves complex problems by breaking them into smaller subproblems.

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.

When to Use Recursion:


30 | P a g e
 When a problem can be broken down into similar subproblems.
 When the depth of recursion is limited to prevent overflow.
 In problems related to tree and graph traversal.

Conditional Statements and Loops in Python

1. Conditional Statements

Conditional statements help control the flow of a program based on certain


conditions. Python provides three types of conditional statements:
a. if-else Statement
Syntax:
if condition:
# Code block if condition is True
else:
# Code block if condition is False
Example:
water_level = 50
if water_level >= 80:
print("Drain water")
else:

31 | P a g e
print("Continue")

Example (Check even or odd):


var_n = int(input("Enter a number to check if it's even or odd: "))
if var_n % 2 == 0:
print("The number is even")
else:
print("The number is odd")

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

Example (Printing squares):


numbers = [1, 2, 3, 4, 5]
squares = []

for num in numbers:


squares.append(num ** 2)

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

3. Examples and Programs

a. Print first n even numbers using while loop:


n = int(input("Enter the value of n: "))
i=0

while i <= n:
if i % 2 == 0:
print("Even number:", i)
i += 2

b. Print first n even numbers using for loop:


n = int(input("Enter the value of n: "))

for i in range(n + 1):


if i % 2 == 0:
print("Even number:", i)

c. Print squares of even numbers using while loop:


n = int(input("Enter the value of n: "))
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: "))

for i in range(2, n + 1, 2):


print(f"Square of {i} is", i ** 2)

Break, Continue, and Pass Statements in Python

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

Example 1: Using break in a for loop


for letter in "TECHIN IT COLLEGE":
if letter == " ":
break
print(letter)
print("The end")
Output:
T
E
C
H
I
N
The end

Example 2: Using break to find a specific number


for num in [11, 9, 88, 10, 90, 3, 19]:
print(num)
if num == 88:
print("The number 88 is found. Terminating the loop.")
break
Output:
11
9
88

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

Example 1: Skipping a character


for letter in "Python":
if letter == "h":
continue
print("Current Letter:", letter)
Output:
Current Letter: P
Current Letter: y
Current Letter: t
Current Letter: o
Current Letter: n

Example 2: Displaying only odd numbers

for num in [20, 11, 9, 66, 4, 89, 44]:

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

Using pass in functions and classes


def my_function():
pass # Function not implemented yet

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

Punctuation marks: !"#$%&'()*+,-./:;<=>?@[\]^_`{|}~

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.

Basic Array Operations


1. Traversal: Access each element in the array.
2. Insertion: Add an element at a specified index.
3. Deletion: Remove an element from a specified index.
4. Search: Find an element by its value or index.
5. Update: Modify an element at a specified index.

40 | P a g e
Creating an Array in Python
from array import *
array_name = array(typecode, [initializers])

Typecode: Specifies the data type of elements.

Common Typecodes:

Typecode Data Type


b Signed integer (1 byte)

B Unsigned integer (1 byte)

c Character (1 byte)

i Signed integer (2 bytes)

I Unsigned integer (2 bytes)

f Floating point (4 bytes)

d Floating point (8 bytes)

Example: Creating and Traversing an Array


from array import *
arr = array('i', [10, 20, 30, 40, 50])
for x in arr:
print(x)

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

print(arr[0]) # Access first element


print(arr[2]) # Access third element

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)

Example: Array Methods


from array import *
arr = array('i', [10, 20, 30, 40, 50])

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)

print("Index of 40:", arr.index(40))

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

Lists, Tuples, and Dictionaries in Python


Lists
A list is an ordered, mutable collection that allows duplicate elements. Lists can grow
and shrink as needed, and they support various operations.
Creating Lists:
list1 = [1, 2, 3, 'A', 'B', 7, 8, [10, 11]]
print(list1) # Output: [1, 2, 3, 'A', 'B', 7, 8, [10, 11]]

Basic List Operations:

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.

Indexing and Slicing:


L = ['TECHIN IT', 'college', 'TECHIN IT!']
print(L[2]) # Output: TECHIN IT!
print(L[-2]) # Output: college
print(L[1:]) # Output: ['college', 'TECHIN IT!']

Mutability and Aliasing:


Lists are mutable; meaning their contents can change. Aliasing occurs when two
variables point to the same list:
a = [81, 82, 83]
b = a # b is an alias for a
b[0] = 100 # Now a is also [100, 82, 83]

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

Accessing Tuple Items:


x = ('a', 'b', 'c', 'g')
print(x[2]) # Output: c
Tuple Operations:
 Count: x.count(2) returns how many times 2 appears.
 Index: x.index(2) returns the first index where 2 is found.
 Length: Use len(x) to find the number of items.
Tuple Assignment:
You can assign multiple values at once:
tup1 = ('TECHIN IT', 'eng college', '2004', 'cse', 'it', 'csit')
tup2 = (1, 2, 3, 4, 5, 6, 7)

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}

Object-Oriented Programming (OOP)


45 | P a g e
Object-Oriented Programming (OOP) is a programming paradigm that organizes
software design around data, or objects, rather than functions and logic. It promotes the
encapsulation of data and behavior into reusable units, which can help in managing complex
software systems.

Key Concepts of OOP


Classes and Objects:
 Class: A blueprint for creating objects (instances). It defines attributes (data) and
methods (functions) that the objects created from the class will have.
 Object: An instance of a class. It represents a specific implementation of the class
with its own state.
Example:
class Dog:
def __init__(self, name, breed):
self.name = name # Instance variable
self.breed = breed # Instance variable
def bark(self): # Method
print(f"{self.name} says Woof!")
my_dog = Dog("Buddy", "Golden Retriever") # Creating an object
my_dog.bark() # Output: Buddy says Woof!

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

def deposit(self, amount):

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

5. Hybrid Inheritance: A combination of two or more types of inheritance. For example, it


can include both multiple and multilevel inheritance.

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

Overloading and Overriding


 Method Overloading

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.

Using the Module:


import addition
result = addition.add(4, 5) # returns 9
print(result)

Python Standard Library Modules


Python comes with a rich standard library that contains numerous built-in modules.
For example, to access mathematical constants and functions, you can use the math module.
Example: Using math Module
import math
print("The value of pi is", math.pi)

Output:
The value of pi is 3.141592653589793

Importing with Renaming


You can also import a module and give it a different name (alias) for convenience.
Example:
import math as m

54 | P a g e
print(m.pi) # Output: 3.141592653589793

Importing Specific Attributes


If you only need specific attributes or functions from a module, you can use the
from ... import syntax.
Example:
from math import pi
print(pi) # Output: 3.141592653589793

Importing All Names


You can import all attributes from a module using the asterisk (*) symbol. However,
this practice is discouraged as it can lead to conflicts with existing names in your code.
Example:
from math import *
print("The value of pi is", pi)

The datetime Module


Python's datetime module provides classes for manipulating dates and times.
Example 1: Get Current Date and Time
import datetime
# Get the current date and time
now = datetime.datetime.now()
print(now)

Output:
2022-12-27 08:26:49.219717

Example 2: Get Current Date


current_date = datetime.date.today()

55 | P a g e
print(current_date)

Output:
2022-12-27

Attributes of the datetime Module


You can use the dir() function to list all attributes of the datetime module.
print(dir(datetime))

Output:
['MAXYEAR', 'MINYEAR', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__',
'__name__', '__package__', '__spec__', 'date', 'datetime', 'time', 'timedelta', 'timezone', 'tzinfo']

Working with datetime.date


You can create date objects using the datetime.date class.
Example 3: Create a Date Object

d = datetime.date(2022, 12, 25)


print(d) # Output: 2022-12-25

Importing Only the date Class

from datetime import date


d = date(2022, 12, 25)
print(d) # Output: 2022-12-25

Getting Today's Date

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

Formatting Dates and Times


The strftime() method can format date, datetime, or time objects into readable strings.
from datetime import datetime
now = datetime.now()
t = now.strftime("%H:%M:%S")
print("Time:", t)
s1 = now.strftime("%m/%d/%Y, %H:%M:%S")
print("s1:", s1)
s2 = now.strftime("%d/%m/%Y, %H:%M:%S")
Python Regular Expressions (RegEx)
Regular Expressions (RegEx) are powerful tools used for pattern matching and
searching within strings. In Python, the built-in re module provides functionalities to work
with regular expressions effectively.
Importing the re Module
To use regular expressions in Python, you first need to import the re module:
import re

Basic Usage of RegEx


Once the re module is imported, you can begin using its functions to perform various
operations on strings.

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

Common RegEx Functions in Python


The re module provides several functions to work with regular expressions:

FUNCTION DESCRIPTION

findall Returns a list containing all matches

search Returns a Match object if there is a match anywhere in the string

split Returns a list where the string has been split at each match

sub Replaces one or many matches with a specified string

Example of Each Function


1. findall(): Finds all occurrences of the pattern.
txt = "The rain in Spain"
matches = re.findall(r"\bain\b", txt)
print(matches) # Output: ['ain', 'ain']

2. search(): Searches for a pattern in the string.


match = re.search(r"rain", txt)
if match:
print("Found:", match.group()) # Output: Found: rain

3. split(): Splits the string at each match.


split_txt = re.split(r"\s+", txt)

58 | P a g e
print(split_txt) # Output: ['The', 'rain', 'in', 'Spain']

4. sub(): Substitutes matches with a specified string.


new_txt = re.sub(r"Spain", "France", txt)
print(new_txt) # Output: The rain in France

Metacharacters in RegEx
Metacharacters are characters that have special meanings in regular expressions. Here
are some common metacharacters:

Character Description Example


[] A set of characters [a-m]
\ Signals a special sequence or escapes a special character \d (digit)
. Matches any character except newline he..o
^ Matches the start of a string ^hello
$ Matches the end of a string planet$
* Matches zero or more occurrences he.*o
+ Matches one or more occurrences he.+o
? Matches zero or one occurrence he.?o
{} Matches exactly the specified number of occurrences he.{2}o
` Acts as a logical OR `
() Captures and groups (abc)
Example of Using Metacharacters
Here's an example demonstrating the use of metacharacters:
import re
pattern = '^a...s$'
test_string = 'abyss'
result = re.match(pattern, test_string)
if result:
print("Search successful.")
else:
print("Search unsuccessful.")

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

How to Install pip?


pip comes pre-installed with Python versions 3.4 and later. To check if pip is installed on
your system, you can run the following command in the terminal or command prompt:
pip --version

If pip is installed, you will see output similar to this:


pip 19.3.1 from C:\Python37\lib\site-packages\pip (python 3.7)
If you are using an older version of Python or if pip is not installed, you can follow the
official installation instructions found on the pip installation page.

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.

Python Exception Handling


In Python, exceptions are events that disrupt the normal flow of a program's
execution. To prevent abrupt termination and to manage errors gracefully, we use exception
handling through the try...except block.
Python try...except Block
The try...except block allows you to write code that can potentially cause an exception while
providing a way to handle that exception if it occurs.
Syntax:
try:
# code that may cause an exception
except:
# code to run when an exception occurs

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.

Catching Specific Exceptions


You can have multiple except blocks to handle different types of exceptions separately.
Example: Handling Multiple Exceptions
try:
even_numbers = [2, 4, 6, 8]
print(even_numbers[5])
except ZeroDivisionError:
print("Denominator cannot be 0.")
except IndexError:
print("Index Out of Bound.")
Output:
Index Out of Bound.
In this case, accessing an index that doesn't exist in the list raises an IndexError, which is
caught and handled appropriately.
Python try...finally
The finally block is used to execute code regardless of whether an exception occurred
or not. It is useful for cleanup actions, such as closing files or releasing resources.
Example: Using finally Block
try:
numerator = 10
denominator = 0
result = numerator / denominator

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.

Python File I/O


File Input/Output (I/O) refers to reading from and writing to files. In Python, file
operations typically follow these steps:
1. Open a file
2. Read or write (perform operation)
3. Close the file
Opening Files in Python
You can open files using the open() method. This method requires the name of the file and
optionally takes a mode parameter.

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

Examples of Opening Files:

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

Voice Assistant Master Project:

A Voice Assistant Master Project involves building a voice-activated


application that can perform tasks based on spoken commands. The
project typically uses technologies like Python (for backend logic) and
libraries such as SpeechRecognition, Pyttsx3 (text-to-speech), and
Natural Language Processing (NLP) tools. The assistant can handle tasks
like fetching data, setting reminders, controlling smart devices, or
answering questions. The focus is on voice processing, command
interpretation, and integrating external APIs for additional functionalities.
64 | P a g e
MAIN FILE CODE:

import pyttsx3 # type: ignore

import speech_recognition as sr

import wikipedia

import webbrowser

import os

# init pyttsx

engine = pyttsx3.init("sapi5")

voices = engine.getProperty("voices")

engine.setProperty('voice', voices[1].id) # 1 for female and 0 for


male voice

def speak(audio):

engine.say(audio)

engine.runAndWait()

def take_command():

r = sr.Recognizer()

with sr.Microphone() as source:

print("Listening...")

r.pause_threshold = 1

audio = r.listen(source)

try:

print("Recognizing...")

query = r.recognize_google(audio, language='en-in')

print("User said:" + query + "\n")

except Exception as e:

65 | P a g e
print(e)

speak("I didnt understand")

return "None"

return query

if __name__ == '__main__':

speak("HI WELCOME")

speak("How can i help you")

while True:

query = take_command().lower()

if 'wikipedia' in query:

speak("Searching Wikipedia ...")

query = query.replace("wikipedia", '')

results = wikipedia.summary(query, sentences=2)

speak("According to wikipedia")

speak(results)

elif 'are you' in query:

speak("I am amigo developed by Jaspreet Singh")

elif 'open youtube' in query:

speak("opening youtube")

webbrowser.open("youtube.com")

elif 'open google' in query:

speak("opening google")

webbrowser.open("google.com")

elif 'open github' in query:

speak("opening github")

webbrowser.open("github.com")

elif 'open stackoverflow' in query:

speak("opening stackoverflow")

webbrowser.open("stackoverflow.com")

66 | P a g e
elif 'open spotify' in query:

speak("opening spotify")

webbrowser.open("spotify.com")

elif 'open whatsapp' in query:

speak("opening whatsapp")

loc = "C:\\Users\\jaspr\\AppData\\Local\\WhatsApp\\
WhatsApp.exe"

os.startfile(loc)

elif 'play music' in query:

speak("opening music")

webbrowser.open("spotify.com")

elif 'play music' in query:

speak("opening music")

webbrowser.open("spotify.com")

elif 'local disk d' in query:

speak("opening local disk D")

webbrowser.open("D://")

elif 'local disk c' in query:

speak("opening local disk C")

webbrowser.open("C://")

elif 'local disk e' in query:

speak("opening local disk E")

webbrowser.open("E://")

elif 'sleep' in query:

exit(0)

SCREEN SHOTS:

67 | P a g e
68 | P a g e

You might also like