[go: up one dir, main page]

0% found this document useful (0 votes)
9 views42 pages

Python Manual

Bzbsv

Uploaded by

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

Python Manual

Bzbsv

Uploaded by

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

PANIMALAR ENGINEERING COLLEGE

An Autonomous Institution, Affiliated to Anna university, Chennai


A christian minority institution
(JAISAKTHI EDUCATIONAL TRUST)
Approved by All India Council of Technical Education
Bangalore Trunk road, Varadharajapuram, Poonamallee, Chennai - 600123

DEPARTMENT
OF
ELECTRONICS & COMMUNICATION ENGINEERING

REGISTER NUMBER:

NAME OF THE STUDENT:

23ES1312 CODING PRACTICES I LAB


II ECE - III SEMESTER
(ODD SEMESTER)
PANIMALAR ENGINEERING COLLEGE
An Autonomous Institution, Affiliated to Anna university, Chennai
A christian minority institution
(JAISAKTHI EDUCATIONAL TRUST)
Approved by All India Council of Technical Education
Bangalore Trunk road, Varadharajapuram, Poonamallee, Chennai - 600123

BONAFIDE CERTIFICATE
This is a Certified Bonafide Record Book of Mr./Ms.

Register Number submitted for End Semester Practical


examination held on in 23ES1312 CODING PRACTICES I LAB
during Oct/Nov 2025 Examinations.

Faculty In-Charge

EXTERNAL EXAMINER INTERNAL EXAMINER


L T P C
23ES1312 CODING PRACTICES I
0 0 2 1

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

1. Data Types, Variables, Operators.


2. Expressions, Precedence of Operators.
3. Conditional Statements.
4. Built-in Functions including Range, len, input, map
and split.
5. Looping, For and While.
6. User Defined Functions.
7. List.
8. Tuple.
9. Dictionary.
10. Recursion and Lambda Functions.
11. String Handling.
12. Regular Expressions.
13. Packages.
14. Exception Handling.
15. GUI using TKinter.
S.No. Date of Experiment Name Date of Sign
Experiment submission
EXERCISE: 1 VARIABLES, DATA TYPES AND OPERATORS

1. Python Variables - Creating Variables:


 Python has no command for declaring a variable.
 A variable is created the moment you first assign a value to it.
Example:
x=5
y = "John"
print(x)
print(y)
Output:
5
John

2. Python Variables - Assign Multiple Values:


 Python allows you to assign values to multiple variables in one line:
Example:
x, y, z = "Orange", "Banana", "Cherry"
print(x)
print(y)
print(z)
Output:
Orange
Banana
Cherry

3. Python Variables - Global Variables:


 Variables that are created outside of a function (as in all of the examples in
the previous pages) are known as global variables.
 Global variables can be used by everyone, both inside of functions and outside.
Example:
x = "awesome"
def myfunc():
print("Python is " + x)
myfunc()
Output:
Orange
Banana
Cherry

4. Python Data Types:


 In programming, data type is an important concept.
 Variables can store data of different types, and different types can do different things.

Python has the following data types built-in by default, in these categories:
Text Type: str

Numeric Types: int, float, complex

Sequence Types: list, tuple, range

Mapping Type: dict

Set Types: set, frozenset

Boolean Type: bool

Binary Types: bytes, bytearray, memoryview

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:

 Operators are used to perform operations on variables and values.

 In the example below, we use the + operator to add together two values:

Python divides the operators in the following groups:

 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

8. print(6 & 3)// Bitwise operators

Output: 2
EXERCISE: 2 EXPRESSIONS, PRECEDENCE OF OPERATORS.

Operator Precedence and Expression:


 Operator precedence describes the order in which operations are performed.

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

Basic String Operations:


Content:
• Concatenation: +
• Repetition: *
• Indexing: []
• Slicing: [:]
Example Code:
a = "Hello"
b = "World"
c = a + " " + b # Concatenation
Output: Hello World
d=a*3 # Repetition
Output: Hello Hello Hello
e = a[1] #Indexing
Output: e
f = a[1:4] # Slicing
Output: ello
Content:
• str.upper(): #Convert to uppercase
• str.lower(): #Convert to lowercase
• str.strip(): #Remove whitespace
• str.replace(): #Replace substrings
• str.split(): #Split into a list
• str.join(): #Join list elements into a string
Examples Code:
text = " Python Programming "
print(text.upper())
Output: “ PYTHON PROGRAMMING “
print(text.lower())
Output: “ python programming “
print(text.strip(“P”))
Output: “ ython rogramming “
text = " Hello, World! "
cleaned_text = text.strip()
print(cleaned_text)
Output: "Hello, World!"
text = " Python Programming "
print(text.replace("Programming",
"Development")) Output: " Python Development
" print(text.split())
words = text.split()
print(words)
Output: [‘Python’, ‘Programming’]
print(", ".join(["Python", "Java", "C+
+"])) Output: Python, Java, C++
EXERCISE: 4 LIST, TUPLE AND DICTIONATY

 Lists are used to store multiple items in a single variable.


 Lists are one of 4 built-in data types in Python used to store collections of data,
the other 3 are Tuple, Set, and Dictionary, all with different qualities and
usage.
 Lists are created using square brackets:
#Creating Lists:
my_list = [1, 2, 3, 4, 5]
mixed_list = [1, "two", 3.0, [4, 5]]
#Accessing Elements:
print(my_list[0]) # Output: 1
print(my_list[2]) # Output: 3
print(mixed_list[3]) # Output: [4, 5]
print(mixed_list[3][1]) # Output: 5 (accessing an element of a sub-list)
#Negative Indexing:
print(my_list[-1]) # Output: 5
print(my_list[-2]) # Output: 4
#Slicing:
print(my_list[1:4]) # Output: [2, 3, 4]
print(my_list[:3]) # Output: [1, 2, 3]
print(my_list[3:]) # Output: [4, 5]
print(my_list[::2]) # Output: [1, 3, 5] (every second element)
#Modifying Lists:
my_list[2] = 10
print(my_list) # Output: [1, 2, 10, 4, 5]
# Adding elements
my_list.append(6)
print(my_list) # Output: [1, 2, 10, 4, 5, 6]
# Inserting elements
my_list.insert(1, 'a')
print(my_list) # Output: [1, 'a', 2, 10, 4, 5, 6]
# Removing elements
my_list.remove(10)
print(my_list) # Output: [1, 'a', 2, 4, 5, 6]
# Popping elements
popped_element = my_list.pop()
print(popped_element) # Output: 6
print(my_list) # Output: [1, 'a', 2, 4, 5]
#Concatenation:
list1 = [1, 2, 3]
list2 = [4, 5]
combined_list = list1 + list2
print(combined_list) # Output: [1, 2, 3, 4, 5]
#Repetition:
repeated_list = [1, 2] * 3
print(repeated_list) # Output: [1, 2, 1, 2, 1, 2]
#Membership Testing:
print(2 in my_list) # Output: True
print(10 in my_list) # Output: False
#Length:
print(len(my_list)) # Output: 5
#List Comprehensions:
squares = [x**2 for x in range(10)]
print(squares) # Output: [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
#Nested Lists:
nested_list = [[1, 2], [3, 4], [5, 6]]
print(nested_list[1]) # Output: [3, 4]
print(nested_list[1][0]) # Output: 3

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

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

Output: Inside function

Example 2:
def greet(name):
print(f"Hello,
{name}!")
greet("Alice")

Output: Hello, Alice!


Example program - built in functions

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

# Using range(start, stop)


for i in range(2, 6):
print(i)
Outputs: 2 3 4 5

# Using range(start, stop, step)


for i in range(1, 10, 2):
print(i)
Outputs: 1 3 5 7 9

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

#using map(function, iterable)


# Function to square a
number def square(x):
return x * x
# Applying the function to a list of numbers
numbers = [1, 2, 3, 4]
squared_numbers = map(square, numbers)

# Converting map object to list


print(list(squared_numbers))
Outputs: [1, 4, 9, 16]

4. split:
The split method is used with strings to divide a string into a list of substrings based
on a delimiter.

#using str.split(separator, maxsplit)


text = "apple orange banana"
words = text.split()
print(words)
Outputs: ['apple', 'orange', 'banana']

# Splitting with a specific separator


data = "name:age:city"
fields = data.split(':')
print(fields)
Outputs: ['name', 'age', 'city']

# Splitting with a limit on the number of splits


text = "one two three four"
limited_split = text.split(' ', 2)
print(limited_split)
Outputs: ['one', 'two', 'three four']
EXERCISE: 6 CONDITIONAL STATEMENT

 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

LOOPING, FOR AND WHILE:


Basic Syntax: for
for variable in iterable:
# code to execute for each item in the iterable
Examples:
for i in range(5):
print(i)
Output:
0
1
2
3
4

Basic Syntax: while

#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

#while condition with break:


Example:
i=1
while i < 6:
print(i)
if i == 3:
break
i += 1
Output:
1
2
3
#while condition with continue:
Example:
i=0
while i < 6:
i += 1
if i == 3:
continue
print(i)
Output:
1
2
4
5
6
EXERCISE: 7 RECURSION AND LAMBDA

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

print("\n\nRecursion Example Results")


tri_recursion(6)
OUTPUT:
Recursion Example Results
1
3
6
10
15
21
Python Lambda:
 A lambda function is a small anonymous function.
 A lambda function can take any number of arguments, but can only have
one expression.

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

Output: YES! We have a match!

RegEx Functions:

Description

Returns a list containing all matches

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

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

Replaces one or many matches with a string


1. findall() Function:
Example:
import re
#Return a list containing every occurrence of "ai":
txt = "The rain in Spain"
x = re.findall("ai", txt)
print(x)
Output: ['ai', 'ai']

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.

 How to Create Package in Python?


 Create a Directory:
 Add Modules:
 Init File:
 Sub packages:
 Importing:
 Distribution:

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.

 finally Block: Executes regardless of whether an exception was raised or not.


This block is typically used for cleanup actions, such as closing files or releasing
resources.
Example:
try:
value = int("abc") # This will raise a ValueError
result = 10 / 0 # This will raise a
ZeroDivisionError

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

GUI using TKinter: INTRODUCTION

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.

Step-by-Step Tkinter Example

 Let’s create a simple application that includes:


 A window with a title.
 A label to display text.
 An entry widget for user input.
 A button that updates the label based on the input.

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

# Create the main application window


root = tk.Tk()
root.title("Login Page")
root.geometry("300x200")

# Create a label for username


username_label = tk.Label(root, text="Username:")
username_label.pack(pady=5)

# Create an entry widget for username


username_entry = tk.Entry(root)
username_entry.pack(pady=5)

# Create a label for password


password_label = tk.Label(root, text="Password:")
password_label.pack(pady=5)
# Create an entry widget for password (with masked input)
password_entry = tk.Entry(root, show="*")
password_entry.pack(pady=5)

# Create a login button


login_button = tk.Button(root, text="Login", command=login)
login_button.pack(pady=10)

# Start the Tkinter event loop


root.mainloop()

Output:
PROGRAMS

Experiment 1: AREA OF THE TRIANGLE


AIM:

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

a = float(input('Enter first side: '))


b = float(input('Enter second side: '))
c = float(input('Enter third side: '))
s = (a + b + c) / 2
area = (s * (s - a) * (s - b) * (s - c)) ** 0.5
print('The area of the triangle is %0.2f' % area)

OUTPUT:

RESULT:
Thus the area of the triangle program has been executed and the output was observed.

Experiment 2: SHOPPING LIST


AIM:
To write a program that accepts the list of items from the user and add that items into the list.

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

print("\n\nRecursion Example Results")


tri_recursion(6)

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

if (num1 >= num2) and (num1 >= num3):


largest = num1
elif (num2 >= num1) and (num2 >= num3):
largest = num2
else:
largest = num3

print("The largest number between",num1,",",num2,"and",num3,"is",largest)

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:

# Function to check if a number is prime


def is_prime(n):
if n <= 1:
return False
for i in range(2, int(n**0.5) + 1):
if n % i == 0:
return False
return True

# Function to print prime numbers in an interval


def print_primes_in_interval(start, end):
print(f"Prime numbers between {start} and {end} are:")
for num in range(start, end + 1):
if is_prime(num):
print(num, end=' ')
print() # For newline after printing all primes

# Input interval
start = 10
end = 50

# Call the function


print_primes_in_interval(start, end)

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

# Rotate the array


rotated_array = right_rotate(array, k)

print("Original array:", array)


print("Right rotated array by", k, "positions:", rotated_array)

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

# Check for division by zero


if b == 0:
raise ValueError("Cannot divide by zero.")
c=a/b
print(f"The result of {a} / {b} = {c}")

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

# Create the main application window


root = tk.Tk()
root.title("Login Page")
root.geometry("300x200")

# Create a label for username


username_label = tk.Label(root, text="Username:")
username_label.pack(pady=5)

# Create an entry widget for username


username_entry = tk.Entry(root)
username_entry.pack(pady=5)

# Create a label for password


password_label = tk.Label(root, text="Password:")
password_label.pack(pady=5)

# Create an entry widget for password (with masked input)


password_entry = tk.Entry(root, show="*")
password_entry.pack(pady=5)

# Create a login button


login_button = tk.Button(root, text="Login", command=login)
login_button.pack(pady=10)

# Start the Tkinter event loop


root.mainloop()
OUTPUT:

RESULT:

Thus the Python program for creating a graphical user interface (GUI) with Tkinter has been
successfully executed.

You might also like