Python Manual
Python Manual
DEPARTMENT
OF
ELECTRONICS & COMMUNICATION ENGINEERING
REGISTER NUMBER:
BONAFIDE CERTIFICATE
This is a Certified Bonafide Record Book of Mr./Ms.
Faculty In-Charge
COURSE OBJECTIVE
● To impart essential problem-solving skills through
general problem-solving concepts..
● To provide basic knowledge on programming essentials using
Python as implementation Tool.
● To introduce various Collection Data types and Exception handling using Python.
LIST OF EXPERIMENTS
Python has the following data types built-in by default, in these categories:
Text Type: str
Example:
1. x = 5
print(type(x)) // output: <class 'int'> //Getting the Data Type
2. x = 20.5
print(type(x)) // output: <class 'float'>//Setting the Data Type
5. Python Operators:
In the example below, we use the + operator to add together two values:
Arithmetic operators
Assignment operators
Comparison operators
Logical operators
Identity operators
Membership operators
Bitwise operators
Example:
1. x = 12
y=3
print(x / y) // Arithmetic operators
Output: 4
2. x = 5
x += 3
print(x)// Assignment operators
Output: 8
3. x = 5
x &= 3
print(x) // Assignment operators
Output: 1
4. x = 5
y=3
print(x > y) //Comparison operators
Output: True
5. x = 5
print(x > 3 and x < 10) //Logical operators
Output: True
6. x = ["apple", "banana"]
y = ["apple", "banana"]
z=x
print(x is z)
print(x is y)
print(x == y)// Identity operators
Output: True
False
True
7. x = ["apple", "banana"]
print("banana" in x)// Membership operators
Output: True
Output: 2
EXERCISE: 2 EXPRESSIONS, PRECEDENCE OF OPERATORS.
Example:
1. print((6 + 3) - (6 + 3))// Parentheses
Output: 0
2. print(100 + 5 * 3)// precedence
Output: 115
3. print(100 - 3 ** 3)//Exponentiation
Output: 73
4. print(100 + ~3)//Unary plus, unary minus, and bitwise NOT
Output: 96
5. print(8 >> 4 - 2)// Bitwise left and right shifts
Output: 2
Same precedence:
If two operators have the same precedence, the expression is evaluated from left
to right.
Example:
1. print(5 + 4 - 7 + 3)
Output: 5
EXERCISE: 3 STRING OPERATION
TUPLES:
Tuples are used to store multiple items in a single variable.
A tuple is a collection which is ordered and unchangeable.
Tuples are written with round brackets.
#Create a Tuple:
eg:
thistuple = ("apple", "banana", "cherry")
print(thistuple) #Output:('apple', 'banana', 'cherry')
#Tuple Length:
print(len(thistuple)) #Output:3
#Accessing by Index:
my_tuple = (10, 20, 30, 40)
print(my_tuple[0]) # Output: 10
print(my_tuple[2]) # Output: 30
#Negative Indexing:
print(my_tuple[-1]) # Output: 40
print(my_tuple[-2]) # Output: 30
#Slicing:
print(my_tuple[1:3]) # Output: (20, 30)
#Nested Tuple:
nested_tuple = (1, (2, 3), 4)
print(nested_tuple[1]) # Output: (2,
3) print(nested_tuple[1][0]) #
Output: 2 print(nested_tuple[1][1])
# Output: 3
#Unpack Tuple:
tup = (1, 2, 3)
a, b, c = tup
print(a) # Output: 1
print(b) # Output: 2
print(c) # Output: 3
#Joining Multiple Tuples:
tuple1 = (1, 2)
tuple2 = (3, 4)
tuple3 = (5, 6)
combined_tuple = tuple1 + tuple2 + tuple3
print(combined_tuple) # Output: (1, 2, 3, 4, 5, 6)
SETS:
Sets are used to store multiple items in a single variable.
A set is a collection which is unordered, unchangeable*, and unindexed.
#Creating a Set:
my_set = {1, 2, 3, 4, 5}
print(my_set) # Output: {1, 2, 3, 4, 5}
#Adding and Removing Elements:
my_set = {1, 2, 3}
my_set.add(4)
print(my_set) # Output: {1, 2, 3, 4}
my_set.discard(3)
print(my_set) # Output: {1, 2, 4}
#Join Set: There are several ways to join two or more sets in Python.
#Union Method:
set1 = {1, 2, 3}
set2 = {3, 4, 5}
set3 = {5, 6, 7}
combined_set = set1.union(set2, set3)
print(combined_set) # Output: {1, 2, 3, 4, 5, 6, 7}
#Update Method:
set1 = {1, 2, 3}
set2 = {3, 4, 5}
set1.update(set2)
print(set1) # Output: {1, 2, 3, 4, 5}
EXERCISE: 5 PYTHON USER DEFINED FUNCTIONS
A function is a set of statements that take inputs, do some specific computation, and
produce output. The idea is to put some commonly or repeatedly done tasks
together and make a function so that instead of writing the same code again and
again for different inputs, we can call the function. Functions that readily come with
Python are called built-in functions.
Built in function including Range, len, input, map and split.
Syntax:
def function_name():
statements
--
--
Example 1: Here we have created the fun function and then called the fun()
function to print the statement.
def fun():
print(“Inside function”)
#calling function
fun()
Example 2:
def greet(name):
print(f"Hello,
{name}!")
greet("Alice")
1. Range:
The range function generates a sequence of numbers, commonly used in for loops. It
can be called with one, two, or three arguments:
# Using range(stop)
for i in range(5):
print(i)
Outputs: 0 1 2 3 4
2. len:
The len function returns the number of items in an object, such as a list, string, tuple,
or dictionary.
# Length of a list
numbers = [1, 2, 3, 4, 5]
print(len(numbers))
Outputs: 5
# Length of a string
text = "Hello, World!"
print(len(text))
Outputs: 13
3. map
The map function applies a given function to all items in an iterable (like a list or
tuple) and returns a map object (an iterator).
4. split:
The split method is used with strings to divide a string into a list of substrings based
on a delimiter.
Conditional statements in Python allow you to execute different blocks of code based on
certain conditions. The primary conditional statements are if, elif and else.
Basic Syntax:
if condition:
# code to execute if the condition is True
elif another_condition:
# code to execute if the first condition is False but this condition is True
else:
#code to execute if none of the above conditions are True
Examples: if
a = 33
b = 200
if b > a:
print("b is greater than a")
OUTPUT: b is greater than a
Examples: elif
a = 33
b = 33
if b > a:
print("b is greater than a")
elif a == b:
print("a and b are equal")
OUTPUT: a and b are equal
#while condition:
# code to execute while the condition is True
Examples:
i=0
while i < 5:
print(i)
i += 1
Output:
0
1
2
3
4
Recursion:
itself. Python also accepts function recursion, which means a defined function can call
Recursion is a common mathematical and programming concept. It means that a
function calls itself. This has the benefit of meaning that you can loop through data to
reach a result.
Example:
def tri_recursion(k):
if(k > 0):
result = k + tri_recursion(k - 1)
print(result)
else:
result = 0
return result
Syntax
lambda arguments : expression
Example 1:
x = lambda a: a + 10
print(x(5))
OUTPUT: 15
Example 2:
x = lambda a, b, c: a + b + c
print(x(5, 6, 2))
OUTPUT: 13
Lambda in functions:
Example:
def myfunc(n):
return lambda a : a * n
mydoubler = myfunc(2)
print(mydoubler(11))
Output: 22
EXERCISE: 8 REGULAR EXPRESSION & PACKAGES
Introduction:
Regular Expression:
▶ A RegEx, or Regular Expression, is a sequence of characters that forms a search
pattern.
▶ RegEx can be used to check if a string contains the specified search pattern.
RegEx Module:
Python has a built-in package called re, which can be used to work with Regular
Expressions.
Syntax:
import re
Example:
import re
#Check if the string starts with "The" and ends with "Spain":
txt = "The rain in Spain"
x = re.search("^The.*Spain$", txt)
if x:
print("YES! We have a match!")
else:
print("No match")
RegEx Functions:
Description
Returns a list where the string has been split at each match
2. search() Function:
Example:
import re
txt = "The rain in Spain"
x = re.search("\s", txt)
print("The first white-space character is located in position:", x.start())
Output: The first white-space character is located in position: 3
3. split() Function
Example:
import re
#Split the string at every white-space character:
txt = "The rain in Spain"
x = re.split("\s", txt)
print(x)
Output: ['The', 'rain', 'in', 'Spain']
4. sub() Function:
▶ function replaces the matches with the text of your choice:
Example:
import re
#Replace all white-space characters with the digit "9":
txt = "The rain in Spain"
x = re.sub("\s", "9", txt)
print(x)
Output:The9rain9in9Spain
Package:
Introduction:
Python Packages are a way to organize and structure your Python code into
reusable components.
Syntax:
mypackage/
│
├── init .py
├── module1.py
└── module2.py
Example:
Package
|
Marriage_package
|
init .py
print("started working")
cooking.py
def start_cooking():
print("dishes completed")
decoration.py
def start_decoration():
print("decoration
completed")
marriage.py
from marriage_package import decoration, cooking
decoration.start_decoration()
cooking.start_cooking()
Output:
started working
decoration
completed dishes
completed
EXERCISE: 9 Exception Handling.
Exception Handling:
Python Exceptions:
An exception is an unexpected event that occurs during program
execution. Exceptions abnormally terminate the execution of a
program.
Errors that occur when we,
try to open a file(for reading) that does not exist (FileNotFoundError)
try to divide a number by zero (ZeroDivisionError)
try to import a module that does not exist (ImportError) and so on.
Exception handling is implemented using try, except, else and
finally blocks.
Syntax:
try:
# Code that may raise an exception, the try block skipped and control pass to exception
block.
except ExceptionType as e:
# Code that runs if an exception occurs and executes code to handle it then pass to else
block
else:
# Code that runs if no exception occurs when the code that should only run if no
exceptions occur then it pass to finally block.
finally:
# Code that always runs, regardless of whether an exception occurred or not.
Explanation of Blocks:
try Block: Contains the code that might raise an exception. If an exception occurs,
the rest of the try block is skipped, and control passes to the except block.
except Block: Catches the exception and executes code to handle it. You can
specify different types of exceptions to handle different error conditions.
else Block: Executes if no exception was raised in the try block. This block
is optional and can be used for code that should only run if no exceptions
occur.
except ValueError as e:
print(f"ValueError occurred: {e}")
except ZeroDivisionError as e:
print(f"ZeroDivisionError occurred: {e}")
else:
print("No errors occurred.")
finally:
print("Execution complete.")
Output:
ValueError occurred: invalid literal for int() with base 10: 'abc'
EXERCISE: 10 GUI using TKinter
Creating a graphical user interface (GUI) with Tkinter in Python can be straightforward. Out of all the
GUI methods, tkinter is the most commonly used method. It is a standard Python interface to the Tk GUI
toolkit. Python Tkinter is the fastest and easiest way to create GUI applications.
Here’s a step-by-step guide to help you build a basic GUI application with Tkinter.
Example:
import tkinter as tk
from tkinter import messagebox
def login():
username = username_entry.get()
password = password_entry.get()
# Predefined credentials
if username == "rajalakshmi" and password == "password123":
messagebox.showinfo("Login Successful", "Welcome, Rajalakshmi!")
else:
messagebox.showerror("Login Failed", "Invalid username or password.")
Output:
PROGRAMS
To write a program that accepts the lengths of three sides of a triangle as inputs and find the area of the
triangle.
SOURCECODE:
# Python Program to find the area of triangle
OUTPUT:
RESULT:
Thus the area of the triangle program has been executed and the output was observed.
SOURCE CODE:
def add_item(shopping_list):
item = input("Enter the item to add: ")
shopping_list.append(item)
print(f"{item} has been added to your shopping list.")
def main():
shopping_list = []
print("Add Item")
add_item(shopping_list)
if __name__ == "__main__":
main()
OUTPUT:
RESULT:
Thus the shopping list program has been executed successfully and the output was verified.
Experiment 3: FACTORIAL OF A NUMBER
AIM:
To write a program to find the factorial of a number.
SOURCE CODE
def tri_recursion(k):
if(k > 0):
result = k + tri_recursion(k - 1)
print(result)
else:
result = 0
return result
OUTPUT:
RESULT:
Thus the program has executed and the output has been verified.
Experiment 4: DESINGING PATTERN
AIM:
To write a Python program to construct the following pattern, using a nested for loop
SOURCE CODE:
n=5
# Increasing triangle
for i in range(n):
for j in range(i):
print('* ', end="")
print() # Move to the next line after each row
# Decreasing triangle
for i in range(n, 0, -1):
for j in range(i):
print('* ', end="")
print() # Move to the next line after each row
OUTPUT:
RESULT:
Thus the Python program to construct the following pattern, using a nested for loop has been executed and
observed the output.
Experiment 5: LARGEST NUMBER
AIM:
To write a python program to find largest of three numbers.
SOURCE CODE:
num1 = 10
num2 = 14
num3 = 12
OUTPUT:
RESULT:
Thus the python program to find largest of three numbers has been executed and observed the output.
Experiment 6: PRIME NUMBERS
AIM:
To write a Python Program to Print all Prime Numbers in an Interval.
SOURCE CODE:
# Input interval
start = 10
end = 50
OUTPUT:
RESULT:
Thus the Python Program to Print all Prime Numbers in an Interval has been executed and observed the
output.
Experiment 7: RIGHT ROTATE THE ELEMENT OF AN ARRAY
AIM:
To write a Python program to right rotate the elements of an array
SOURCE CODE:
def right_rotate(arr, k):
n = len(arr)
k = k % n # In case k is greater than n
return arr[-k:] + arr[:-k]
# Example usage
array = [1, 2, 3, 4, 5]
k = 2 # Number of positions to rotate
OUTPUT:
RESULT:
Thus the Python program to right rotate the elements of an array has been executed and observed the
output.
Experiment 8: EXCEPTION HANDLING
AIM:
To write a Python program that runs if an exception occurs and executes code to handle.
SOURCE CODE:
try:
# Input numbers from the user
a = float(input("Enter first number: "))
b = float(input("Enter second number: "))
except ValueError as e:
# Handle the division by zero error and invalid input
print(e)
OUTPUT:
RESULT:
Thus the Python program that runs if an exception occurs and executes code to handle has been
observed.
Experiment 9: PYTHON PACKAGE
AIM:
To write a Python program create Package.
SOURCE CODE:
Package
|
Marriage_package
|
init .py
print("started working")
cooking.py
def start_cooking():
print("dishes completed")
decoration.py
def start_decoration():
print("decoration
completed")
marriage.py
from marriage_package import decoration, cooking
decoration.start_decoration()
cooking.start_cooking()
OUTPUT:
RESULT:
Thus the Python program to create a Package has been executed successfully.
Experiment 10: GUI USING TKINTER
AIM:
To write a Python program for creating a graphical user interface (GUI) with Tkinter.
SOURCE CODE:
import tkinter as tk
from tkinter import messagebox
def login():
username = username_entry.get()
password = password_entry.get()
# Predefined credentials
if username == "abc" and password == "password123":
messagebox.showinfo("Login Successful", "Welcome, abc!")
else:
messagebox.showerror("Login Failed", "Invalid username or password.")
RESULT:
Thus the Python program for creating a graphical user interface (GUI) with Tkinter has been
successfully executed.