22csp03 PP Lab QB

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 34

NANDHA ENGINEERING COLLEGE(AUTONOMOUS)

22CSP03- PYTHON PROGRAMMING LAB


QUESTION BANK

YEAR/SEM : I/II ACADEMIC YEAR:2023-2024

1. Programs for demonstrating the use of different types of operators.

1.A. Rajesh runs a small business and wants to calculate the profit percentage he
made on a particular sale. He needs a program that takes the cost price (cp), the
rate of appreciation (ra), and the selling price (sp) as input, and calculates the profit
percentage. Help Rajesh by writing a program that takes the cost price, rate of
appreciation, and selling price, and computes the profit percentage.

Output value should be displayed correct to 2 decimal places.

PROGRAM:
cp = int(input())
ra = int(input())
sp = int(input())
cp += ra
sp -= cp
print("{:.2f}".format(sp*100/cp))

INPUT

4700
800
5800

OUTPUT
5.45
1.
1.B. Write a program that solves the following problem:
You have a square and a rectangle
1. The side of the square is of length 10 cm. Assign this value to the
variables.
2. The sides of the rectangle have length 25cm and breadth 17cm.
3. Assign these values to the variables l and b respectively
4. The cost of painting the square is Rs. 4 per cm^2.
calculate the cost of painting a square with a given side length at a
specified cost per square cm.

PROGRAM:
s = 17
areas = s*s
l = 19
b = 18
arear = l*b
areadiff = arear - areas
costs = areas * 4
print("The area of Square is", areas )
print("The area of Rectangle is", arear )
print("The difference of areas is", areadiff)
print("Cost of painting the Square is", costs)

OUTPUT:
The area of Square is 289
The area of Rectangle is 342
The difference of areas is 53
Cost of painting the Square is 1156
1.C. We have the variable a = 0b10111011.Use a bitmask and the value
a in order to achieve a result where all of the bits in a are flipped. Be
sure to print your answer as a bin() string.

PROGRAM:
a = 0b10111011
bitmask = int('1' * len(bin(a)[2:]), 2)
flipped_a = a ^ bitmask
print("Flipped a:", bin(flipped_a))

OUTPUT:
Flipped a: 0b10111100
2. Programs for demonstrating control statements

2.A. Fazil needs a triangle classification program. Given sides side1,


side2, and side3, determine if it's Equilateral, Isosceles, or Scalene based
on the following conditions:
 If all sides are equal, classify as Equilateral.
 If exactly two sides are equal, classify as Isosceles.
 If all sides are different, classify as Scalene.
Input Format
The input consists of the three floating-point numbers side1, side2, and
side3, representing the lengths of the sides of a triangle, separated by a
line.
Output Format
The output is the classification of the triangle based on its sides.
The output should be a single line containing the classification as a
string.

PROGRAM:
side1 = float(input())
side2 = float(input())
side3 = float(input())
triangle_type = ""
if side1 == side2 and side2 == side3:
triangle_type = "Equilateral"
if side1 == side2 and side2 != side3 or side1 != side2 and side2 == side3
or side1 == side3 and side2 != side3:
triangle_type = "Isosceles"
if side1 != side2 and side2 != side3 and side1 != side3:
triangle_type = "Scalene"
print(f"The triangle is classified as {triangle_type}")
INPUT
90.0
90.0
90.0
OUTPUT
The triangle is classified as Equilateral
2.B. Write a Python program that takes a person's age as input and
determines their life stage based on the following criteria:
"Child" if the age is 12 or below.
"Teen" if the age is between 13 and 19 (inclusive).
"Adult" if the age is 20 or above
Input Format:
A single integer value representing the person's age.
Output Format:
A single string that says either "Child", "Teen", or "Adult".
PROGRAM:
age = int(input("Enter the age: "))
if age <= 12:
print("Child")
elif age <= 19:
print( "Teen")
else:
print( "Adult")
INPUT:
Enter the age:13
OUTPUT:
Teen

2.C. Write a Python program that reads an integer N from the user and
then reads N integers. The program should calculate the product of all
positive numbers and the sum of all negative numbers from the provided
integers. Finally, it should output these two results.
Input Format:
The first line contains an integer N (1 ≤ N ≤ 100), the number of integers to
follow.
The next N lines each contain one integer ai(-1000 ≤ ai≤ 1000).
Output Format:
The first line should contain the product of the positive numbers.
The second line should contain the sum of the negative numbers.
PROGRAM:
N = int(input("Enter the number of integers: "))
positive_product = 1
negative_sum = 0
has_positive = False
for i in range(N):
number = int(input())
if number > 0:
positive_product *= number
has_positive = True
elif number < 0:
negative_sum += number
if has_positive:
print("Product of positive numbers:", positive_product)
else:
print("Product of positive numbers: 0")
print("Sum of negative numbers:",negative_sum)
INPUT:
Enter the number of integers: 5
3
-2
4
-1
0
OUTPUT:
Product of positive numbers: 12
Sum of negative numbers: -3
3. Programs to implement various string operations.

3.A. PROBLEM STATEMENT:


Write a Python program toadd 'ing' atthe end ofa given string (length
should beat least 3). If the given string already ends with 'ing', add 'ly'
instead.If the string length of the given string is less than 3,leave it
unchanged.
Sample String:'abc’
Expected Result: 'abcing’
Sample String: 'string’
Expected Result: 'stringly’

AIM:
To write a Python program that modifies a given string by adding 'ing' at the end if its length
is atleast 3.If the string already ends with'ing', add'ly' instead.If the string length is less than 3, leave it
unchanged.

ALGORITHM:
STEP 1: Start
STEP 2: Define a function add_string that takes one parameter str1, which is the input string.
STEP 3: Get the length of the input string using len(str1) and store it in the variable length.
STEP 4: Check if the length of the string is greater than 2.
STEP 5: If the length is greater than 2:
a. Check if the last three characters of the string (str1[-
3:]) are equal to 'ing'.
b. If they are, append 'ly' to the string (str1 += 'ly').
c. If not, append 'ing' to the string (str1 += 'ing').

STEP 6: Return the modified string str1.


STEP 7 : Test the function with different inputs to ensure it behaves as expected.
PROGRAM:
defadd_string(str1):
length=len(str1)
if length > 2:
ifstr1[-3:]=='ing':
str1 += 'ly'
else:
str1+='ing'
return str1
print(add_string('ab'))
print(add_string('abc'))
print(add_string('string'))
OUTPUT:
ab
abcing
stringly

3.B. PROBLEM STATEMENT:


Write a Python program to get a string madeof the first2 andlast 2
characters of a given string.If the string length is less than 2,return the
empty string instead.
Sample String: 'w3resource'
Expected Result: 'w3ce'
Sample String: 'w3'
Expected Result: 'w3w3'
Sample String: ' w'
Expected Result: Empty String

AIM:
To Write a Python program to get a string madeof the first2 and last 2 characters of a given
string.If the string length is less than 2,return the empty string instead.

ALGORITHM:
STEP 1: Start.
STEP 2: Function Definition: The string_both_ends function takes a single parameter, str,
which is the input string.
STEP 3: Check Length: It first checks if the length of the input string is less than 2 (if
len(str) < 2).
If it is, the function returns an empty string ''
STEP 4: Concatenation: If the length of the input string is greater than or equal to 2, the
function returns a string Containing the first two characters of the input string (str[0:2])
concatenated with the last two characters of the input string (str[-2:]).
STEP 5: Return: The resulting concatenated string is returned.
STEP 6: Test Cases: The function is tested with three different input strings using the print
statements.
STEP 7: End.
PROGRAM:
def string_both_ends(str):
iflen(str) < 2:
return ''
returnstr[0:2] + str[-2:]
print(string_both_ends('w3resource'))
print(string_both_ends('w3'))
print(string_both_ends('w'))
OUTPUT:
w3ce
w3w3
3.C. PROBLEM STATEMENT:
Write a Python program to remove unwanted characters from a given
string.
Original String :Pyth*^on Exercis^es
After removing unwanted characters: Python Exercises
Original String : A%^!B#*CD
After removing unwanted characters: ABCD
AIM:
To write a Python program that removes unwanted characters from a given string,
leaving only alphanumeric characters.

ALGORITHM:
STEP 1: Start
STEP 2: Input: Take the original string str1 and a list of unwanted characters
unwanted_chars.
STEP 3: Initialize an empty string: Create an empty string result to store the modified string.
STEP 4: Iterate through each character in the original string: Loop through each character in
str1.
STEP 5: Check if the character is unwanted: For each character, check if it exists in the list
unwanted_chars.
STEP 6: Append to result if not unwanted: If the character is not in unwanted_chars, append
it to the result string.
STEP 7: Return the result: Once all characters have been processed, return the modified
string result.
STEP 8: End

PROGRAM:
def remove_chars(str1,unwanted_chars):for i in unwanted_chars:
str1=str1.replace(i,'')return str1
str1="Pyth*^onExercis^es"str2= "A%^!B#*CD"
unwanted_chars=["#","*","!","^","%"]
print("OriginalString:"+str1)
print("Afterremovingunwantedcharacters:")
print(remove_chars(str1,unwanted_chars))
print("\nOriginalString:"+str2)
print("Afterremovingunwantedcharacters:")
print(remove_chars(str2,unwanted_chars))

OUTPUT:
OriginalString:Pyth*^on Exercis^es After
removing unwanted characters:
PythonExercises
OriginalString:A%^!B#*CD
Afterremovingunwantedcharacters:
ABCD
4. Programs for demonstrating the following
i. Lists
ii. Tuples
iii. Dictionaries

i. Lists
4.1.1. Problem Statement

Write a Python program to find common elements that takes two lists as input and
returns a new list containing the common elements between the two input lists.
Input Format
The first line consists of space-separated integers representing the elements of the
first list.
The second line consists of space-separated integers representing the elements of
the second list.
Output Format
The output prints the common elements between the given two lists.
If there are no common elements, the output prints the empty list.

4.1.2. Problem Statement:

Write a Python program that takes a sentence as input and returns a new sentence
with the words reversed.

4.1.3. Problem Statement

Write a Python program to sort a list according to the length of the elements.

ii. Tuple

4.2.1. Problem Statement

Gowshik is working on a task that involves taking two lists of integers as input,
finding the element-wise sum of the corresponding elements, and then creating a
tuple containing the sum values.

Write a program to help Gowshik with this task.


Example:

Given tuples:
(1, 2, 3, 4)
(3, 5, 2, 1)

An element-wise sum of the said tuples: (4, 7, 5, 5)

4.2.2.Problem Statement

Write a Python program to find the length of a tuple.


Input Format
The input consists of a tuple of strings.
Output Format
The output prints an integer, representing the length of the tuple.

4.2.3.Problem Statement

Given a list of numbers of list, write a Python program to create a list of tuples
having the first element as the number and the second element as the cube of the
number.
Input Format
The first line of input consists of an integer, representing the size of the list N.
The following N lines of input consist of the integers, representing the elements of
the list.
Output Format
The output displays the list of tuples with a cube of each number in the input list.

iii. Dictionary

4.3.1. Problem Statement

Write a Python program that takes an integer n as input and then takes n key-value
pairs as input to populate a dictionary my_dict. Each key is a string, and the
corresponding value is an integer.

The program should then find and print the three highest values in the dictionary in
descending order.
4.3.2. Problem Statement

Write a Python program to sort a dictionary based on its values in ascending order.
Input Format
The first line contains the keys of the given dictionary as space-separated elements.
The second line contains the values of the given dictionary as space-separated
elements.
Output Format
The output displays the given dictionary in ascending order in separate lines in the
format: "[key] : [value]".

4.3.3. Problem Statement

Ram did grocery shopping. He has a list of items along with the quantity he bought
and price of each item. Can you please help him to find the total amount he spent.

Create a list of dictionaries with each dictionary has item name, quantity and price.
For example,
[
{ "product": "Milk", "quantity": 1.5, "price": 10.5},
{ "product": "Eggs", "quantity": 12.0, "price": 0.25}
]

Pass this dictionary to the function and get the total sum of the amount Ram spent
in grocery shop. Round the output to 2 decimal places.
5. Programs to demonstrate concepts using functions

5.1 PROBLEM STATEMENT


Create a program that takes the height and radius of a cone as arguments
and returns the volume of the cone and rounds the output to 2 decimal
places (Use the round function). Use the math module to get the value of pi.

Formula to calculate the Volume of a cone, V = PI * (radius)2 * height / 3

Input Format
The first line of the input consists of an integer that represents the height.
The second line of the input consists of an integer which represents the
radius.

Output Format
The output prints the volume of the cone rounding off to two decimal
places.

PROGRAM
import math
def cone_volume(h, r):
return round((1/3)*math.pi*(r**2)*h,2)
m=int(input())
n=int(input())
print(cone_volume(m, n))
Input
2
8
Output
134.04

5.2 PROBLEM STATEMENT

Write a Python function to find the maximum of three numbers a, b, and c.

Function prototype: def max_of_three(a,b,c)


Input Format
The input consists of three integers a, b, and c in separate lines.

Output Format
The output displays the maximum of the three numbers a, b, and c.

Program
def max_of_two( x, y ):
if x > y:
return x
return y

def max_of_three(a,b,c):
return max_of_two( a, max_of_two(b,c))

a = int(input())
b = int(input())
c = int(input())
print(max_of_three(a,b,c))
Input:
10
50
-100
Output
50

5.3 PROBLEM STATEMENT

You are given a non-negative integer n. Your task is to calculate the sum of
powers of 2 from 0 to n (inclusive) using math module.

Implement a function findSum(n) that takes an integer n as input and


returns the sum of 2^0 + 2^1 + 2^2 + ... + 2^n.
Input Format
The input contains one integer N.
Output Format
The output displays a single integer representing the sum of powers of 2
from 0 to n.

Refer sample input and output for formatting specifications.


Constraints
0 ≤ N ≤ 10000
PROGRAM
import math

def findSum(n):
s=0
for i in range(0, n + 1):
s += math.pow(2, i)
return s

n = int(input())
print(findSum(n))

Input
8
Output
511.0

6. Programs to implement applications using File handling

6.1 PROBLEM STATEMENT


Write a function in python to count the number of lines from a text file
"story.txt" which is not starting with an alphabet "T".
Example: If the file "story.txt" contains the following lines: A boy is
playing there.
There is a playground.
An aeroplane is in the sky.
The sky is pink.
Alphabets and numbers are allowed in the password.
The function should display the output as 3

Program
def line_count():
file = open("story.txt","r")
count=0
for line in file:
if line[0] not in 'T':
count+= 1
file.close()
print("No of lines not starting with 'T'=",count)

line_count()

6.2 PROBLEM STATEMENT


Create a file named "story.txt" and write a function display_words() in
python to read lines from a text file "story.txt", and display those words,
which are less than 4 characters.

Program

def display_words():
file = open("poem.txt","r")
data = file.read()
words = data.split()
for word in words:
if len(word) < 4:
print(word, end=" ")
file.close()

display_words()

6.3 PROBLEM STATEMENT


Write a function in Python to read lines from a text file "notes.txt". Your
function should find and display the occurrence of the word "the".
For example: If the content of the file is:
"India is the fastest-growing economy. India is looking for more
investments around the globe. The whole world is looking at India as a
great market. Most of the Indians can foresee the heights that India is
capable of reaching."
The output should be 5.
Program
def count_words():
file = open("notes.txt","r")
count = 0
data = file.read()
words = data.split()
for word in words:
if word =="the" or word =="The":
count += 1
print(count)
file.close()

count_words()

7. Programs to demonstrate modules.


7.1) Create a program that takes the height and radius of a cone as
arguments and returns the volume of the cone and rounds the output to 2
decimal places (Use the round function). Use the math module to get the
value of pi.
Formula to calculate the Volume of a cone, V = PI * (radius)2 * height / 3

Input Format
The first line of the input consists of an integer that represents the height.
The second line of the input consists of an integer which represents the radius.

Output Format
The output prints the volume of the cone rounding off to two decimal places.
Refer to the sample output for the formatting specifications.

Constraints
1 <= height, radius <= 100

Sample Input Sample Output


5256.56
7
Output:

Test CaseInputOutput
2134.04
8
Weightage – 20InputOutput
123216.99
16
Weightage – 25InputOutput
34282024.96
89
Weightage – 30InputOutput
1114110.99
35
Weightage – 25Sample InputSample Output
5256.56
7

Solution
import math
defcone_volume(h, r):
return round((1/3)*math.pi*(r**2)*h,2)
m=int(input())
n=int(input())
print(cone_volume(m, n))

7.2) Write a Python program that uses regular expressions to validate


whether a given password is strong or not. A strong password should
satisfy the following conditions:
It should have at least eight characters.
It should contain at least one uppercase letter.
It should contain at least one lowercase letter.
It should contain at least one digit.
It should contain at least one special character from the set [!@#$%^&*(),.?":{}|<>].

Input Format
The input will be a single line containing the password to be checked.

Output Format
The program will output one of the following messages:
If the given password is strong, the program will print "The password is strong"
Otherwise, it will print "The password is not strong"

Constraints
The password can contain any printable ASCII characters.
The length of the password should be at most 100 characters.

Sample Input Sample Output


Secret@007The password is strong

Sample Input Sample Output


AbcdefghThe password is not strong

Output:

Test CaseInput Output


Th1$isH@rd The password is strong
Weightage – 10Input Output
MyP@ss The password is not strong
Weightage – 10Input Output
Str0ng@P@ssw0rd! The password is strong
Weightage – 15Input Output
Pass@word123 The password is strong
Weightage – 15Input Output
Abcdefgh123@#$! The password is strong
Weightage – 25Input Output
C0mpl3x_P@$$ The password is strong
Weightage – 25Sample Input Sample Output
Secret@007 The password is strong
Sample Input Sample Output
Abcdefgh The password is not strong

Solution
import re
defis_strong_password(password):
# Check if the password has at least eight characters
iflen(password) < 8:
return False

# Check if the password contains at least one uppercase letter


if not re.search(r'[A-Z]', password):
return False

# Check if the password contains at least one lowercase letter


if not re.search(r'[a-z]', password):
return False

# Check if the password contains at least one digit


if not re.search(r'\d', password):
return False

# Check if the password contains at least one special character


if not re.search(r'[!@#$%^&*(),.?":{}|<>]', password):
return False

return True

def main():
password = input()
ifis_strong_password(password):
print("The password is strong")
else:
print("The password is not strong")

if __name__ == "__main__":
main()

7.3) Write a Python function that takes a text, an old word, and a new word
as input, and replaces all occurrences of the old word with the new word in
the text.
Input Format
The first line consists of the strings as a text in which you need to find and replace the old word.
The second line consists of the string that needs to be replaced.
The third line consists of the string to replace.

Output Format
The output prints the updated text after replacing all occurrences of the old word with the new
word.

Refer to the sample output for the formatting specifications.


Sample Input Sample Output
Python is an easy-to-learn programming language. Java is an easy-to-learn programming
language.Python is widely used for web development.Java is widely used for web development.
Python
Java
Sample Input Sample Output
Regular expressions are powerful tools Regular expressions are useful tools for text processing and
pattern matching.for text processing and pattern matching.
powerful
useful

Output:

Test CaseInput Output


Alice had a little lamb. The lamb was white as snow.Alice had a little sheep.
Everywhere that Alice went, the lamb was sure to go. The sheep was white as snow.
LambThe sheep was white as snow.
SheepEverywhere that Alice went,
the sheep was sure to go
Weightage – 15Input Output
The sun is shining. The sun is warm.The moon is shining.
sun The moon is warm.
moon
Weightage – 10Input Output
I have three cats and two dogs. I have three cats and five dogs
two
five
.
Weightage – 10Input Output
This is a test sentence.The test is important. This is a evaluate sentence.
We will test it thoroughly.The evaluate is important.
test We will evaluate it thoroughly.
evaluate

Weightage – 15Input Output


The weather is unpredictable.The climate is unpredictable.
I wonder what the weather will be like tomorrow.I wonder what the climate will be
weatherlike tomorrow.
climate

Weightage – 25Input Output


The old house on the hill was haunted.The old mansion on the hill was haunted.
Many people claimed to have Many people claimed to have seen seen ghosts in the
house.ghosts in the mansion.
house
mansion

Solution
import re
defreplace_word(text, old_word, new_word):
pattern = r'\b' + re.escape(old_word) + r'\b'
updated_text = re.sub(pattern, new_word, text)
returnupdated_text

input_text = input()
old_word = input()
new_word = input()

updated_text = replace_word(input_text, old_word, new_word)


print(updated_text)

8. Programs to implement applications using regular expression.

8.1) Write a function that takes a piece of text as input and extracts all the
integers (whole numbers) from the given text.
The function should use regular expressions to identify and extract the integers correctly.
Input Format
The input consists of a string containing alphanumeric characters, special characters, and spaces,
and may include integers in various formats.
Output Format
The output prints a list of strings representing the extracted integers from the input text.

Refer to the sample output for the formatting specifications.


Constraints
The input string contains 100 characters.
Sample Input Sample Output
I have 10 apples and 5 oranges ['10', '5']

Sample Input Sample Output


The room number is 2023 ['2023']

Output:

Test CaseInput Output


The temperature is -5 degrees Celsius ['5']
Weightage – 10Input Output
The car's top speed is 250 km/h ['250']
Weightage – 10Input Output
The population of the city is approximately 1,500,000 ['1', '500', '000']
Weightage – 15Input Output
The recipe requires 2.5 cups of flour and 1.75 cups of milk ['2', '5', '1', '75']
Weightage – 15Input Output
The distance between the two cities is 123.45 kilometres ['123', '45']
Weightage – 25Input Output
The product's dimensions are 15.25 inches x 10.75 inches x 5 inches['15', '25', '10', '75', '5']
Weightage – 25Sample Input Sample Output
I have 10 apples and 5 oranges ['10', '5']
Sample Input Sample Output
The room number is 2023 ['2023']
Solution
import re
defextract_integers(text):
pattern = r'\b\d+\b'
integers = re.findall(pattern, text)
return integers
text = input()
result = extract_integers(text)
print(result)

8.2)Write a python program to replace all occurrences of \e with e using


regular expression.
Note:
Use import re
Input Format
The input is a string
Output Format
The output is a string after replacingall occurrences of '\e' with 'e'.

Refer to the sample output for the formatting specifications.


Constraints
The input string consists of the 100 characters.
Sample Input Sample Output
This is an \exampl\e of a t\estcas\e This is an example of a testcase
Sample Input Sample Output
This is anoth\er t\estcas\e This is another test case

Output :

Test CaseInput Output


th\e day was v\ery b\eautiful the day was very beautiful
Weightage – 50Input Output
python is a high l\ev\el languag\e python is a high level language
Weightage – 30Input Output
s\earch for diamonds h\er\e search for diamonds here
Weightage - 20 Input Output
This is an \exampl\e of a t\estcas\e This is an example of a testcase
Sample Input Sample Output
This is anoth\er t\estcas\e This is another test case
Solution

import re
ip = input()
print(re.sub(r'\\e', 'e', ip))

8.3) Write a Python program so that for the given input list, it filters all
elements that contain the number 42 surrounded by word characters using
regular expression.
Note:
import re

Input Format
The first input is the N value which is an integer.
The next input is the list of strings as per the value of N.
Output Format
The output is a list of string which has characters in and around 42

Refer to the sample input and output for format specifications.


Sample Input Sample Output
4 ['cat42kitten', 'duck42duckling']
cat42kitten
dog42
duck42duckling
hen
Sample Input Sample Output
3 ['taj42mahal']
taj42mahal
pisatower42
pyramids

Output :

Test CaseInput Output


3 ['cat42dog']
cat42dog
good
goo42
Weightage – 40Input Output
3 ['white42blocak', 'block42pge']
morn42
white42blocak
block42pge
Weightage – 30Input Output
3 ['rahul42kapoor', 'ria42malhotra']
rahul42kapoor
ria42malhotra
dia42
Weightage – 20Input Output
3 ['better42best', 'awesome42wonderful']
better42best
bad42
awesome42wonderful
Weightage - 10Sample Input Sample Output
4 ['cat42kitten', 'duck42duckling']
cat42kitten
dog42
duck42duckling
hen
Sample Input Sample Output
3 ['taj42mahal']
taj42mahal
pisatower42
pyramids

Solution
import re
words=[]
n=int(input())
for i in range(n):
words.append(input())
print([w for w in words if re.search(r'\B42\B', w)])

9. Program to demonstrate GUI.

PROBLEM STATEMENT:

Write a Python GUI program to design a paint application using Tkinter where the user can draw
on the Canvas widget with different colors
AIM:
To write a Python GUI program using the tkinter module that creates an paint application
using Tkinter where the user can draw on the Canvas widget with different colors.

ALGORITHM:

Step 1: Start

Step 2: Import the tkinter module.

Step 3: Define global variables to track the drawing state (drawing), last coordinates (last_x, last_y),
and pen color (pen_color).

Step 4: start_drawing: Sets drawing to True and initializes last_x and last_y

Step 5: stop_drawing: Sets drawing to False when the drawing action is stopped

Step 6: draw: Draws lines on the canvas if drawing is True

Step 7: Define a function change_color to update the pen_color based on the button clicked

Create the main Tk instance and set the window title

Step 8: Create a Canvas widget where drawing will happen, set its dimensions and background color.

Step 9: Create buttons for different pen colors using a list of predefined colors.

Step 10: Each button is associated with the change_color function using lambda to pass the color as
an argument.

Step 11: Bind mouse events (<Button-1>, <ButtonRelease-1>, <B1-Motion>) to the canvas and
associate them with the corresponding event handler functions (start_drawing, stop_drawing, draw)

Step 12: Finally, start the main event loop using root.mainloop() to display the GUI and handle user
interactions.

Step 13:Stop

PROGRAM:
import tkinter as tk

drawing = False

last_x, last_y = None, None


pen_color = "black"

def start_drawing(event):

global drawing

drawing = True

global last_x, last_y

last_x, last_y = event.x, event.y

def stop_drawing(event):

global drawing

drawing = False

def draw(event):

global last_x, last_y

if drawing:

x, y = event.x, event.y

canvas.create_line((last_x, last_y, x, y), fill=pen_color, width=2)

last_x, last_y = x, y

def change_color(new_color):

global pen_color

pen_color = new_color

root = tk.Tk()

root.title("Paint Application")
canvas = tk.Canvas(root, width=400, height=300, bg="white")

canvas.pack()

colors = ["red", "green", "blue", "black", "orange", "pink"]

color_buttons = []

for color in colors:

color_buttons.append(tk.Button(root, text=color.capitalize(), bg=color, command=lambda c=color:


change_color(c)))

color_buttons[-1].pack(side=tk.LEFT)

canvas.bind("<Button-1>", start_drawing)

canvas.bind("<ButtonRelease-1>", stop_drawing)

canvas.bind("<B1-Motion>", draw)

root.mainloop()

Output:
RESULT:

Thus the python programming for GUI has been Executed and verified successfully

10. Perform data manipulation using NumPy.

10.1. PROBLEM STATEMENT:


Write a NumPy program to create a 3x3 matrix with values ranging from 2
to 10.
Expected Output:

[[ 2 3 4]

[ 5 6 7]

[ 8 9 10]]

AIM:
To write a NumPy program that creates a 3x3 matrix with values ranging from 2 to 10.

ALGORITHM:

STEP 1: Start

STEP 2: Import NumPy: Import the NumPy library to use its functionalities.

STEP 3: Define Range and Step:

-Define the starting value (start) of the range as 2.


- Define the ending value (stop) of the range as 11 (since range() function is exclusive of the stop value).

- Define the step size (step) as 1.

STEP 4: Create Array Using np.arange():

- Use np.arange() function to generate an array of numbers from start to stop with the specified step.

- Example: array_values = np.arange(start, stop, step)

STEP 5: Reshape Array:

- Reshape the array_values to a 3x3 matrix using the reshape() method.

- Example: matrix = array_values.reshape(3, 3)

STEP 6: Output the Matrix:

- Print or display the generated matrix.

STEP 7: End

PROGRAM:

importnumpy as np

x = np.arange(2, 11).reshape(3, 3)

print(x)

OUTPUT:

[[ 2 3 4]

[ 5 6 7]

[ 8 9 10]]

RESULT:

Thus the python programming for Numpy module has been Executed and verified successfully.
10.2. PROBLEM STATEMENT:
Write a NumPy program to append values to the end of an array.
Expected Output:

Original array:

[10, 20, 30]

After append values to the end of the array:

[10 20 30 40 50 60 70 80 90]

AIM:

To write a NumPy program that appends values to the end of an array.

ALGORITHM:

STEP 1: Start

STEP 2: Import NumPy: Import the NumPy library to use its functionalities.

STEP 3: Initialize an Array: Create an initial NumPy array with some values.

STEP 4: Define Values to Append: Decide on the values you want to append to the array.

STEP 5: Append Values:

- Use NumPy'snp.append() function to append the values to the array.

- Specify the array to which you want to append (array) and the values (values_to_append).

- Store the result in a new array variable or update the original array if needed.

STEP 6: Output the Updated Array: Print or display the array after appending the values.

PROGRAM:

importnumpy as np

x = [10, 20, 30]

print("Original array:")
print(x) x = np.append(x, [[40, 50, 60], [70, 80, 90]])

print("After append values to the end of the array:")

print(x)

OUTPUT:

Original array:

[10, 20, 30]

After append values to the end of the array:

[10 20 30 40 50 60 70 80 90]

RESULT:

Thus the python programming for Numpy module has been Executed and verifiedsuccessfully.

10.3. PROBLEM STATEMENT:


Write a NumPy program to find common values between two arrays.
Expected Output:

Array1: [ 0 10 20 40 60]

Array2: [10, 30, 40]

Common values between two arrays:

[10 40]

AIM:

To write a NumPy program to find common values between two arrays.

ALGORITHM:

STEP 1: Start
STEP 2: Import NumPy: Import the NumPy library to use its functionalities.

STEP 3: Initialize Arrays: Create two NumPy arrays with some values.

STEP 4: Find Common Values:

- Use NumPy'snp.intersect1d() function to find the intersection of elements between the two arrays.

- Pass the two arrays as arguments to np.intersect1d().

- Store the result in a new array variable to hold the common values.

STEP 5: Output the Common Values: Print or display the array containing the common values.

PROGRAM:

importnumpy as np

array1 = np.array([0, 10, 20, 40, 60])

print("Array1: ", array1)

array2 = [10, 30, 40]

print("Array2: ", array2)

print("Common values between two arrays:")

print(np.intersect1d(array1, array2))

OUTPUT:

Array1: [ 0 10 20 40 60]

Array2: [10, 30, 40]

Common values between two arrays:

[10 40]

RESULT:
Thus the python programming for Numpy module has been Executed and verified
successfully.

You might also like