0% found this document useful (0 votes)
4 views49 pages

Python Programs

Uploaded by

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

Python Programs

Uploaded by

vishnugopu.k
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Python Programming [ Lab Programs ]

☛ I. Use a web browser to go to the Python website [Link] This


page contains information about Python and links to Python-related pages, and it
gives you the ability to search the Python documentation.

II. Start the Python interpreter and type help() to start the online help utility.

Solution :

I. Use a web browser to go to the Python website [Link] This


page contains information about Python and links to Python-related pages, and it
gives you the ability to search the Python documentation.

In this tutorial we are going to learn about installation of Python3


on ✍ Windows and ✍Linux (Ubuntu)

✍ Python installation procedure in Windows :

To install Python in windows, we have to download Python software pack from official
website of Python Software Foundation.
1. Go to [Link]

The following page will displayed on your web browser.


2. Go to Downloads:

The following page will displayed on your web browser.


3. Download the latest version of python(now latest version:python 3.13.7) for
windows

4. After the successful completion of download, we need to run python-


[Link] file

Then the Python setup window will be displayed as shown in below.

5. Click on Install Now

First we need to check Add Python 3.13.7 to PATH, And then click on Install
Now, the Python setup progress window will be displayed as shown in below.
6. Setup was Successful

The Python setup will take 2 to 3 minutes of [Link] successful installation the
following window will be displayed
7. Click on Close button

That's it, Python Setup was Successful

Python Documentaion:

1. Go to python official website [Link]


->click on documentation page
2. Click on Python Docs, then the following window will be displayed.

3. Select version
4. Select topic

✍ Python3 installation procedure in Linux (Ubuntu) :

All most all Linux (Ubuntu) operating systems came up with python 2. 7. To check
the python version in your Linux (Ubuntu) system, open terminal by pressing Ctrl + ALT
+ T and then type following command press enter.
$ python --version (or) $ python -V

Then we get version of python i.e. Python 2.7.12

In this tutorial we are going to install Python 3 on Linux (Ubuntu) Operating System.

To install Python 3

1. To update software packages on your system, execute the following command in


terminal

$ sudo apt-get update

2. After successful updating of software packages, To install python3, execute the


following command in terminal

$ sudo apt-get install python3

3. To check if python is install properlyor not, we will check the version of python

$ python3 --version (or) $ python3 -V

Then we get version of python3 i.e. Python 3.13.x i.e, Python3 setup successful in
Linux (Ubuntu) operating system.

II. Start the Python interpreter and type help() to start the online help utility.

To Start the Python interpreter in your Linux (Ubuntu) system, open terminal by
pressing Ctrl + ALT + T and then type following command press enter.
$ python3

And then type following command press enter.

>>> help()

The following is the sample output screenshot


-------------------------------------------------------------------------------------------------------------
2. Start a Python interpreter and use it as a Calculator.

Solution :

To Start the Python interpreter in your Linux (Ubuntu) system, open terminal by
pressing Ctrl + ALT + T and then type following command press enter.

$ python3

And then type following


Integer to Integer :

>>> a = 10
>>> b = 30

>>> print ( type ( a ) )


< class ' int ' >

>>> print ( type ( b ) )


< class ' int ' >

>>> print ( a + b )
40

>>> print ( a - b )
-20

>>> print ( a * b )
300

>>> print ( a / b )
0.3333333333333333

>>> print ( a % b )
10

>>> print ( a ** b )
1000000000000000000000000000000

>>> print ( a // b )
0

Integer to Float :

>>> a = 10
>>> b = 3.25

>>> print (type(a))


< class ' int ' >

>>> print (type(b))


< class ' float ' >

>>> print ( a + b )
13.25

>>> print ( a - b )
6.75

>>> print ( a * b )
32.5

>>> print ( a / b )
3.076923076923077

>>> print ( a % b )
0.25

>>> print ( a ** b )
1778.2794100389228

>>> print ( a // b )
3.0

Float to Float :

>>> a = 6.78
>>> b = 2.34

>>> print (type(a))


< class ' float ' >

>>> print ( type ( b ) )


< class ' float ' >

>>> print ( a + b )
9.120000000000001

>>> print ( a - b )
4.44
>>> print ( a * b )
15.8652

>>> print ( a / b )
2.897435897435898

>>> print ( a % b )
2.1000000000000005

>>> print ( a ** b )
88.12060773350571

>>> print ( a // b )
2.0

Integer to String :
>>> a = 6
>>> b = " python "

>>> print ( type ( a ) )


< class ' int ' >

>>> print ( type ( b ) )


< class ' str ' >

>>> print ( a + b )
TypeError: unsupported operand type(s) for + : ' int ' and ' str '

>>> print ( a - b )
TypeError: unsupported operand type(s) for - : ' int ' and ' str '

>>> print ( a * b )
python python python python python python

>>> print ( a / b )
TypeError: unsupported operand type(s) for / : ' int ' and ' str '

>>> print ( a % b )
TypeError: unsupported operand type(s) for % : ' int ' and ' str '

>>> print ( a ** b )
TypeError: unsupported operand type(s) for ** : ' int ' and ' str '

>>> print ( a // b )
TypeError: unsupported operand type(s) for // : ' int ' and ' str '

String to String :

>>> a = " python "


>>> b = " Programming "

>>> print ( type ( a ) )


< class ' str ' >
>>> print ( type ( b ) )
< class ' str ' >

>>> print ( a + b )
python Programming

>>> print ( a - b )
TypeError: unsupported operand type(s) for - : ' str ' and ' str '

>>> print ( a * b )
TypeError: unsupported operand type(s) for * : ' str ' and ' str '

>>> print ( a / b )
TypeError: unsupported operand type(s) for / : ' str ' and ' str '

>>> print ( a % b )
TypeError: unsupported operand type(s) for % : ' str ' and ' str '

>>> print ( a ** b )
TypeError: unsupported operand type(s) for ** : ' str ' and ' str '

>>> print ( a // b )
TypeError: unsupported operand type(s) for // : ' str ' and ' str '

Integer to Complex :

>>> a = 9
>>> b = 3 + 4j

>>> print ( type ( a ) )


< class ' int ' >

>>> print ( type ( b ) )


< class ' complex' >

>>> print ( a + b )
( 12 + 4j )
>>> print ( a - b )
( 6 - 4j )

>>> print ( a * b )
( 27 + 36j )

>>> print ( a / b )
( 1.08 - 1.44j )

>>> print ( a % b )
TypeError: unsupported operand type(s) for % : ' int ' and ' complex '

>>> print ( a ** b )
( - 586.5166552058375 + 432.9425056126467j )

>>> print ( a // b )
TypeError: unsupported operand type(s) for //: ' int ' and ' complex '

Float to Complex :

>>> a = 4.83
>>> b = 3 + 4j

>>> print ( type ( a ) )


< class ' float ' >

>>> print ( type ( b ) )


< class ' complex' >

>>> print ( a + b )
( 7.83 + 4j )

>>> print ( a - b )
( 1.83 - 4j )

>>> print ( a * b )
( 14.49 + 19.32j )
>>> print ( a / b )
TypeError: unsupported operand type(s) for / : ' int ' and ' complex '

>>> print ( a % b )
TypeError: unsupported operand type(s) for % : ' int ' and ' complex '

>>> print ( a ** b )
( 112.66380061063158 + 1.8253767513645904j )

>>> print ( a // b )
TypeError: unsupported operand type(s) for //: ' int ' and ' complex '

-------------------------------------------------------------------
3. Write a program to calculate compound interest when principal, rate and
number of periods are given.

Solution :

The formula to calculate compound interest annually is given by:


A = P ( 1 + R / 100 )t
Compound Interest = A - P

Where,
A is amount,
P is the principal amount
R is the rate of interest,
T is the time span

PROGRAM: ([Link])

# Python program to compute compound interest


p = int(input(" Enter the principal amount : "))
t = float(input(" Enter the time in years : " ))
r = float(input(" Enter the rate of interest : "))
# compute compound interest
amount = p * (pow((1 + r / 100), t))
ci = amount - p
# print
print(" Compound Interest : " , ci )

OUTPUT:

Enter the principal amount : 50000


Enter the time in years : 3.8
Enter the rate of interest : 2
Compound Interest : 3907.6819031304913

-------------------------------------------------------------------------------------------------------------

4. Read the name, address, email and phone number of a person through the
keyboard and print the details.

Solution :

PROGRAM: ([Link])

Name = input("Enter Person Name : ")


Address = input("Enter Person Address : ")
Email = input("Enter Person Email : ")
Phone_no = input("Enter Phone number : ")
print(" Please Confirm your provided Information\n " )
print(" Person Name : " ,Name )
print(" Person Address : " , Address )
print(" Person Email : " , Email )
print(" Person Phone_no : " , Phone_no )

OUTPUT:

Enter Person Name: Madhu


Enter Person Address : HYDERABAD
Enter Person Email : madhu@[Link]
Enter Person Phone_no : 9656123456
Please Confirm your provided Information
Person Name : Madhu
Person Address : HYDERABAD
Person Email : madhu@[Link]
Person Phone_no : 9656123456

-------------------------------------------------------------------

5. Print the below triangle using for loop.

5
44
333
2222
11111

Solution :

PROGRAM: ([Link])

Num = int( input ( "Enter no of rows = " ) )


# reverse for loop from 5 to 1
for i in range ( 1 , Num + 1 ) :
for j in range ( i ) :
print ( Num , end = ' ' )
Num -= 1
print ( ' ' )

OUTPUT:

Enter no of rows = 5
5
44
333
2222
11111

-------------------------------------------------------------

6. Write a program to check whether the given input is digit or lowercase


character or uppercase character or a special character(use 'if-else-if' ladder)

Solution :

PROGRAM: (check_input_char.py)

ch = input ( " Enter a character : " )


if ( ord ( ch ) >= 65 and ord ( ch ) <= 90 ) :
print ( ch , " is Upper Case Character " )
elif ( ord ( ch ) >= 97 and ord ( ch ) <= 122 ) :
print ( ch , " is Lower Case Character " )
elif ( ord ( ch ) >= 48 and ord ( ch ) <= 57 ) :
print ( ch , " is Digit " )
else:
print ( ch , " is Symbol " )

OUTPUT:

Sample Run 1:
Enter a character : 5
5 is Digit

Sample Run 2:
Enter a character : H
H is Upper Case Character

Sample Run 3:
Enter a character : b
b is Lower Case Character

Sample Run 4:
Enter a character : @
@ is Symbol

-----------------------------------------------------

7. Python program to print all prime numbers in a given interval (use break)

Solution :

PROGRAM: (prime_numbers.py)

lower_value = int ( input ( "Enter the Lowest Range Value: " ) )


upper_value = int ( input ( "Enter the Upper Range Value: " ) )
print ( "Prime numbers between " , lower_value , " and " , upper_value , " are : " )
for num in range ( lower_value , upper_value + 1 ) :
# all prime numbers are greater than 1
if num > 1 :
for i in range ( 2 , num) :
if ( num % i ) == 0 :
break
else :
print ( num , end = " \t " )

OUTPUT:

Enter the Lowest Range Value: 5


Enter the Upper Range Value: 36
Prime numbers between 5 and 36 are :
5 7 11 13 17 19 23 29 31

-------------------------------------------------------------------
8. Write a program to convert a list and tuple into arrays

Solution :

PROGRAM: ([Link])

import numpy as np
list = [ 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 ]
print ( " List to array: " )
array_1 = np . asarray ( list )
print ( type ( array_1 ) )
print ( array_1 )
print ( )
print ( )
tuple = ( [ 8, 4 , 6 ] , [ 1 , 2 , 3 ] )
print ( " Tuple to array: " )
array_2 = np . asarray ( tuple )
print ( type ( array_2 ) )
print ( array_2 )

OUTPUT:

List to array:
< class ' numpy . ndarray ' >
[12345678]
Tuple to array:
< class ' numpy . ndarray ' >
[[846]
[123]]

--------------------------------------------------------

9. Write a program to find common values between two arrays

Solution :
PROGRAM: (common_values.py)

import numpy as np
array1 = np . array ( [ 5, 10 , 20 , 40 , 60 ] )
print ( " Array1 : " , array1 )
array2 = np . array ( [10 , 30 , 40 ] )
print ( " Array2 : " , array2 )
print ( " Common values between two arrays are : " )
print ( np . intersect1d ( array1 , array2 ) )

OUTPUT:

Array1 : [ 5 10 20 40 60 ]
Array2 : [ 10 30 40 ]
Common values between two arrays are :
[ 10 40 ]

----------------------------------------------------------------
10. Write a function called palindrome that takes a string argument
and returnsTrue if it is a palindrome and False otherwise. Remember that you can
use the built-in function len to check the length of a string.

Solution :

PROGRAM: (palindrome_str. py)

def Palindrome(str):
# Run loop from 0 to len/2
for i in range( 0 , int (len(str) / 2)):
if str[i] != str[len(str) - i - 1 ]:
return False
return True
# main function
s = input(" Enter any string to check palindrome = ")
boolean = Palindrome(s)
if (boolean):
print( s , " is palindrome ")
else :
print( s , " is not palindrome ")

OUTPUT:

Sample Output - 1:
Enter any string to check palindrome = MADAM
MADAM is palindrome

Sample Output - 2:
Enter any string to check palindrome = SIR
SIR is not palindrome

----------------------------------------------------------
11. Write a function called is_sorted that takes a list as a parameter and returns
True if the list is sorted in ascending order and False otherwise.

Solution :

PROGRAM: (is_sorted.py)

def is_sorted(user_list):
new_list = sorted(user_list)
print(" Your Sorted list : " , sorted(user_list))
if(new_list == user_list):
return True
else:
return False
user_list = [int(x) for x in input("Please enter a list: ").split()]
print(" Your list : " , user_list)
print(is_sorted(user_list))
OUTPUT:

Please enter a list: 7 8 9 4 5 6 10 12


Your list : [7, 8, 9, 4, 5, 6, 10, 12]
Your Sorted list : [4, 5, 6, 7, 8, 9, 10, 12]
False

--------------------------------------------------------
[Link] a function called has_duplicates that takes a list and returns True if there
is any element that appears more than once. It should not modify the original list.

Solution :

PROGRAM: (has_duplicates.py)

def has_duplicate(my_list):
for k in my_list:
if my_list.count(k) > 1 :
return True
break
else :
return False
user_list = input(" Please enter a list : ").split()
print(" Your list : " , user_list)
res = has_duplicate ( user_list )
if res :
print( " The list contain duplicate values ")
else :
print( " The list not contain duplicate values ")

OUTPUT:

Sample Output 1:
Please enter a list : 6 7 2 3 1 3 1 8 6
Your list : [ '6' , '7' , '2' , '3' , '1' , '3' , '1' , '8' , '6' ]
The list contain duplicate values

Sample Output 2:
Please enter a list : 6 7 2 3 1 8 9
Your list : [ '6' , '7' , '2' , '3' , '1' , '8' , '9' ]
The list not contain duplicate values

-----------------------------------------------------
[Link] a function called remove_duplicates that takes a list and returns a new
list with only the unique elements from the original. Hint: they don't have to be in
the same order.

Solution :

PROGRAM: (remove_duplicates.py)

def remove_duplicates(my_list):
for k in my_list :
if my_list . count(k) > 1 :
del my_list[my_list.index(k)]
user_list = input(" Please enter a list : ").split()
print(" Your list : " , user_list)
remove_duplicates(user_list)
print(" Your list without duplicates : \n " , user_list)

OUTPUT:

Please enter a list : 6 7 2 3 1 3 1 8 6


Your list : [ '6' , '7' , '2' , '3' , '1' , '3' , '1' , '8' , '6' ]
Your list without duplicates :
[ '7' , '2' , '3' , '1' , '8' , '6' ]

-------------------------------------------------------------------
[Link] wordlist I provided, [Link], doesn't contain single letter words. So you
might want to add "I", "a", and the empty string.

Solution :

Text File:[Link]

PROGRAM: (single_letter.py)

def load_words(filename):
with open(filename, "r") as file:
words = [[Link]() for line in file]

# Add missing single-letter words and empty string


if "" not in words:
[Link]("")
if "I" not in words:
[Link]("I")
if "a" not in words:
[Link]("a")

return words
# Sample usage
words = load_words("[Link]")
print("Total number of words:", len(words))
print("Sample words:", words[:10])

OUTPUT:
Total number of words: 8
Sample words: ['apple', 'banana', 'cat', 'dog', 'elephant', '', 'I', 'a']

-------------------------------------------------------------

[Link] a python code to read dictionary values from the user. Construct a
function to invert its content. i.e., keys should be values and values should be
keys.

Solution :

PROGRAM: (invert_dictionary.py)

import ast
def swap_dict(old_dict):
return { value : key for key , value in old_dict.items () }
old_dict = input(" Please enter a dictionary : \n ")
old_dict = ast.literal_eval(old_dict)
# Printing original dictionary
print(" Original dictionary is : \n " , old_dict)
print()
new_dict = swap_dict(old_dict)
# Printing new dictionary
print(" New dictionary is : \n " , new_dict)

OUTPUT:

Please enter a dictionary :


{ 'A' : 65 , 'B' : 66 , 'C' : 67 , 'D' : 68 , 'E' : 69 , 'F' : 70 , 'G' : 71 , 'H' : 72 }
Original dictionary is :
{'A': 65, 'B': 66, 'C': 67, 'D': 68, 'E': 69, 'F': 70, 'G': 71, 'H': 72}

New dictionary is :
{65: 'A', 66: 'B', 67: 'C', 68: 'D', 69: 'E', 70: 'F', 71: 'G', 72: 'H'}

--------------------------------------------------------
[Link] a comma between the characters. If the given word is 'Apple', it should
become 'A,p,p,l,e'.

Solution :

PROGRAM: (add_comma.py)

def add_comma(x):
return ','.join(x)

in_str = "Apple"
print(add_comma(in_str))

OUTPUT:

A,p,p,l,e

---------------------------------------------------------

17. Remove the given word in all the places in a string?

Solution :

PROGRAM: (remove_words.py)

def remove_all_words(in_str,sub):
my_list = in_str.split( )
for i in my_list :
if i == sub :
del my_list[my_list.index(i)]
final_string = ' '
for i in my_list :
final_string = final_string + i + ' '
return final_string
str_in = input(" Enter any string = ")
sub = input(" Enter sub string ( which word you want to delete ) = ")
result = remove_all_words(str_in , sub)
print(" Updated string after removal sub_string : \n " , result)

OUTPUT:

Enter any string = Hai, this is python, welcome to Study Glance


Enter sub string ( which word you want to delete ) = Study
Updated string after removal sub_string :
Hai, this is python, welcome to Glance

---------------------------------------------------------

[Link] a function that takes a sentence as an input parameter and replaces the
first letter of every word with the corresponding upper case letter and the rest of
the letters in the word by corresponding letters in lower case without using a
built-in function?

Solution :

PROGRAM: (replace_first.py)

def replace_first(str_in):
x = list(str_in)
i=0
while i < len(x):
# consider first character of word
if i == 0 :
if ord(x[i]) >= 97 and ord(x[i]) <= 122 :
x[i] = chr(ord(x[i]) - 32)
elif x[i] == ' ':
i=i+1
if ord(x[i]) >= 97 and ord(x[i]) <= 122 :
y = ord(x[i])
x[i] = chr(y - 32)
else :
if ord(x[i]) >= 65 and ord(x[i]) <= 92 :
x[i] = chr(ord(x[i]) + 32)
i=i+1
str_out = ' '
for j in x :
str_out = str_out + j
return str_out

str_in = input(" Enter any string = ")


str_op = replace_first(str_in)
print(str_op)

OUTPUT:

Enter any string = welcome TO STUdy glance


Welcome To Study Glance

---------------------------------------------

[Link] a recursive function that generates all binary strings of n-bit length.

Solution :

PROGRAM: (binary_strings.py)

def generate_binary_number(length, binary_string):


if len(binary_string) == length:
print(binary_string)
return

generate_binary_number(length, binary_string + '0')


generate_binary_number(length, binary_string + '1')

n = int(input("Enter number of bits to generate binary set = "))


print("Binary numbers are: ")
generate_binary_number(n, '')

OUTPUT:

Enter number of bits to generate binary set = 3


Binary numbers are:
000
001
010
011
100
101
110
111

-------------------------------------------------------------------
[Link] a python program that defines a matrix and prints.

Solution :

PROGRAM: (matrix_print.py)

R = int(input(" Enter the number of rows : "))


C = int(input(" Enter the number of columns : "))
# Initialize matrix
matrix = []
print(" Enter the entries row - wise : ")
# For user input
for i in range(R):
a = []
for j in range(C):
[Link](int(input()))
[Link](a)
print()

# For printing the matrix


print(" Matrix Values are: \n ")
for i in range(R) :
for j in range(C):
print(matrix[i][j] , end = " ")
print()

OUTPUT:

Enter the number of rows : 3


Enter the number of columns : 3
Enter the entries row - wise :
1
2
3
4
5
6
7
8
9

Matrix Values are:

123
456
789
--------------------------------------------------

[Link] a python program to perform multiplication of two square matrices.

Solution :

In this program we use "numpy" package to create matrices. So we need to


install "numpy" package using the following commands.

To Install in Windows:
pip install numpy

To Install in Linux:

Python programming course

sudo apt-get install numpy

PROGRAM: (matrix_mul.py)

import numpy as np
a = [Link]([[ 1 , 2 ] , [ 4 , 5 ]])
b = [Link]([[ 6 , 5 ] , [ 3 , 2 ]])
c = [Link](a,b)
print(" Multiplication of two Square Matrices is \n " , c)

OUTPUT:

Multiplication of two Square Matrices is


[[12 9]
[39 30]]

----------------------------------------------------

[Link] do you make a module? Give an example of construction of a module


using different geometrical shapes and operations on them as its functions.

Solution :

PROGRAM: ([Link])

from math import pi


def rectangle(l,b):
return l * b
def square(s):
return s * s
def circle(r):
return pi * r * r
def triangle(l,b):
return 1 / 2 * l * b

PROGRAM: (geometrical_shapes.py)

import area
l = int(input(" Enter value of height = "))
b = int(input(" Enter value of width = "))
s = int(input(" Enter value of side = "))
r = int(input(" Enter value of radius = "))

print(" Area of rectangle = " , [Link](l,b))


print(" Area of square = " , [Link](s))
print(" Area of circle = " , [Link](r))
print(" Area of triangle = " , [Link](l,b))

OUTPUT:

Enter value of height = 6


Enter value of width = 6
Enter value of side = 6
Enter value of radius = 6
Area of rectangle = 36
Area of square = 36
Area of circle = 113.09733552923255
Area of triangle = 18.0

---------------------------------------------------

[Link] the structure of exception handling all general-purpose exceptions.

Solution :
PROGRAM: (exception_handling.py)

def function(a,b):
c=a/b
print ( c )
try :
a = int(input(" Enter a value : "))
b = int(input(" Enter b value : "))
function(a,b)
except ValueError :
print(" Value Error Occurred \t Pease Enter Correct integer Values ")
except ZeroDivisionError :
print(" Zero Division Error Occurred \t Can't division by zero ")
else :
print(" Successfully executed without errors ")

OUTPUT:

Sample Run 1:
Enter a value : 5
Enter b value : 0
Zero Division Error Occurred Can't division by zero

Sample Run 2:
Enter a value : 5
Enter b value : 3
1.6666666666666667
Successfully executed without errors

Sample Run 3:
Enter a value : 5
Enter b value : d
Value Error Occurred Pease Enter Correct integer Values

--------------------------------------------------------------
24. Write a function called draw_rectangle that takes a Canvas and a Rectangle as
arguments and draws a representation of the Rectangle on the Canvas.

Solution :

PROGRAM: (draw_rectangle.py)

from tkinter import *


# Create an instance of tkinter frame
root = Tk ()
# Create Title
[Link](" Rectangle ")
# create canvas object
widget = Canvas(root, width = 700 , height = 400 , bg = "grey")
#function
def draw_rectangle(windget,rect):
print(rect)
# Read Co-ordinates
x1 = int(input(" Enter x1 value = " ))
y1 = int(input(" Enter y1 value = " ))
x2 = int(input(" Enter x2 value = " ))
y2 = int(input(" Enter y2 value = " ))
# create object for rectangle
rect = widget.create_rectangle(x1,y1,x2,y2)
# call function by passing canvas & rectangle objects as argument
draw_rectangle(widget,rect)
[Link]()
[Link]()

OUTPUT:

Enter x1 value = 100


Enter y1 value = 30
Enter x2 value = 250
Enter y2 value = 100

----------------------------------------------
[Link] an attribute named color to your Rectangle objects
and modify draw_rectangle so that it uses the color attribute as the fill color.

Solution :

PROGRAM: (fill_rectangle. py)

from tkinter import *


# Create an instance of tkinter frame
root = Tk ()
# Create Title
[Link](" Rectangle ")
# create canvas object
widget = Canvas(root, width = 700 , height = 400 , bg = "grey")
#function
def draw_rectangle(windget,rect):
print(rect)
# Read Co-ordinates
x1 = int(input(" Enter x1 value = " ))
y1 = int(input(" Enter y1 value = " ))
x2 = int(input(" Enter x2 value = " ))
y2 = int(input(" Enter y2 value = " ))
# create object for rectangle
rect = widget.create_rectangle(x1,y1,x2,y2,fill="red")
# call function by passing canvas & rectangle objects as argument
draw_rectangle(widget,rect)
[Link]()
[Link]()

OUTPUT:

Enter x1 value = 100


Enter y1 value = 30
Enter x2 value = 250
Enter y2 value = 100
-------------------------------------------------------------------------------------------

[Link] a function called draw_point that takes a Canvas and a Point as


arguments and draws a representation of the Point on the Canvas.

Solution :

PROGRAM: (draw_point.py)

from tkinter import *


# Create an instance of tkinter frame or window
win = Tk ()
# Create Title
[Link](" Draw - point ")
# Set the size of the window
[Link]("700x350")
# Define a function to draw the line between two points
def draw_point(event):
x1= event.x
y1= event.y
x2= event.x
y2= event.y
# Draw an oval in the given co-ordinates
canvas.create_oval(x1,y1,x2,y2,fill="black",width = 20 )
# Create a canvas widget
canvas = Canvas(win,width = 650,height = 300,background = "white")
[Link](row = 0 ,column = 0)
[Link]('<Button-1>',draw_point)
click_num = 0
[Link]()

OUTPUT:

-----------------------------------------------------------------------------------------------------

[Link] a new class called Circle with appropriate attributes and instantiate a
few Circle objects. Write a function called draw_circle that draws circles on the
canvas.

Solution :

PROGRAM: (draw_circle.py)
from tkinter import *
#Create an instance of tkinter frame
root = Tk()
# Create Title
[Link](" Circle ")
# create canvas object
widget = Canvas(root, width=500,height=400 , bg = "brown" )
#function
def draw_circle(widget,circle):
print(circle)
# Read Co-ordinates
x1 = int(input(" Enter x1 value = "))
y1 = int(input(" Enter y1 value = "))
x2 = int(input(" Enter x2 value = "))
y2 = int(input(" Enter y2 value = "))
# create object for rectangle
circle = widget.create_oval(x1 , y1 , x2 , y2 , fill = "#000fff000")
# call function by passing canvas & rectangle objects as argument
draw_circle(widget,circle)
[Link]()
[Link]()

OUTPUT:
-------------------------------------------------------------------

[Link] a python code to read a phone number and email-id from the user
and validate it for correctness.

Solution :

PROGRAM: (validate_phmail.py)

import re
# Make a regular expression for validating an Email
regex = r'^\b[A-Za-z0-9._%+-]+[@]\w[A-Za-z]+[.]\w[A-Z|a-z]{2,5}$'
# Make a regular expression for validating a Phone Number
Pattern = '^\\+?[6-9][0-9]{9}$'
# Define a function for validating an Email
def is_check_email(email):
if([Link](regex,email)):
print(" Valid Email - ID ")
else:
print(" Invalid Email - ID ")
# Define a function for validating a PHONE NUMBER
def is_check_Phone_number(mobile_no):
if([Link](Pattern,mobile_no)):
print(" Valid Phone Number ")
else:
print(" Invalid Phone Number ")
# Driver Code
if __name__ == '__main__':
email = input(" Enter your MAIL-ID = ")
phone_number = input(" Enter your PHONE NUMBER = ")
is_check_email(email)
is_check_Phone_number(phone_number)

OUTPUT:

Sample Run 1:
------------
Enter your MAIL-ID = study@[Link]
Enter your PHONE NUMBER = 9758456123
Valid Email - ID
Valid Phone Number

Sample Run 2:
------------
Enter your MAIL-ID = study%are@[Link]
Enter your PHONE NUMBER = 1234567890
Valid Email - ID
Invalid Phone Number

Sample Run 3:
------------
Enter your MAIL-ID = glance@gmail - 3 .com
Enter your PHONE NUMBER = 8945621231
Invalid Email - ID
Valid Phone Number

---------------------------------------------------------------
[Link] a Python code to merge two given file contents into a third file.

Solution :

PROGRAM: (merge_files.py)

# Open the source text file - 1


file1 = open('[Link]','r')
content1 = [Link]()
[Link]()
# Open the source text file - 2
file2 = open('[Link]','r')
content2 = [Link]()
[Link]()
# Open the destination file to merge content
file3 = open('[Link]','w')
[Link](content1 + content2 )
[Link]()
# Print merge text file
file3 = open('[Link]','r')
print([Link]())
[Link]()

OUTPUT:

Hai Study Glance


How are You?
---------------------------------------------------------------------------------------------------------
[Link] a Python code to open a given file and construct a function to check for
given words present in it and display on found.

Solution :

PROGRAM: (check_words.py)

def search_str(file_path):
search_word = input(" Enter a word you want to search in file : ")
with open(file_path , 'r') as file :
# read all content of a file
content = [Link]()
# check if string present in a file
for word in content :
if [Link](search_word) != -1:
print('The search word exists in the file & available at line =
' ,[Link](word))
break
else :
print(" string does not exist in a file ")
[Link]()

file = open("[Link]",'w')
Lines = ["Hai \n ","This is Python Programming \n ","Welcome to study glance \n "]
[Link](Lines)
[Link]()
search_str('[Link]')

OUTPUT:

Enter a word you want to search in file : to


string does not exist in a file
string does not exist in a file
The search word exists in the file & available at line = 2
-----------------------------------------------------------------
[Link] a Python code to Read text from a text file, find the word
with most number of occurrences.

Solution :

Input Data file ("[Link]"):

This is Study Glance. Study Galnce provides various Study related meterials.

PROGRAM: (most_word.py)

count = 0
word = " "
max_Count = 0
words = []

#Opens a file in read mode


file = open("[Link]" , "r")
#Gets each line till end of file is reached
for line in file :
#Splits each line into words
string = [Link]().replace(',',' ').replace('.','').split(" ");
#Adding all words generated in previous step into words
for s in string:
[Link](s)

#Determine the most repeated word in a file


for i in range(0,len(words)):
count = 1
#Count each word in the file and store it in variable count
for j in range(i+1 , len(words)):
if(words[i] == words[j]):
count = count + 1
# If maxCount is less than count then store value of count in maxCount
# and corresponding word to variable word
if (count > max_Count):
max_Count = count
word = words[i]
print(" Most repeated word is = " + word)
[Link]()

OUTPUT:

Most repeated word is = study

---------------------------------------------------------------
[Link] a function that reads a file file1 and displays the number of words,
number of vowels, blank spaces, lower case letters and uppercase letters.

Solution :

Input Data file ("[Link]"):

Hello python
this is study glance
123 456

PROGRAM: ([Link])

def counting(filename):
txt_file = open(filename , "r")
no_of_vowels = 0
no_of_words = 1
no_of_lines = 1
no_of_spaces = 0
no_of_uppercase = 0
no_of_lowercase = 0
no_of_digits = 0
# Make a vowels list
vowels_list = ['a','e','i','o','u','A','E','I','O','U']
# Iterate over the characters present in file
for ch in txt_file.read():
if ch == "\n" or ch == ' ':
no_of_words = no_of_words + 1
if ch == ' ':
no_of_spaces = no_of_spaces + 1
if ch in vowels_list:
no_of_vowels = no_of_vowels + 1
if ch == "\n":
no_of_lines = no_of_lines + 1
if(ord(ch) >= 97 and ord(ch) <= 122):
no_of_lowercase = no_of_lowercase + 1
if(ord(ch) >= 65 and ord(ch) <= 90):
no_of_uppercase = no_of_uppercase + 1
if(ord(ch) >= 48 and ord(ch) <= 57):
no_of_digits = no_of_digits + 1
# Print the desired output on the console.
print(" Number of vowels = ", no_of_vowels)
print(" Number of words = " , no_of_words)
print(" Number of Blank spaces = " , no_of_spaces)
print(" New Lines = " , no_of_lines)
print(" Number of lower case characters in = " , no_of_lowercase)
print(" Number of upper case characters = " , no_of_uppercase)
print(" Number of digits = " , no_of_digits)
# Driver Code
filename = input(" Enter text file name = ")
counting(filename)

OUTPUT:

Enter text file name = [Link]


Number of vowels = 8
Number of words = 8
Number of Blank spaces = 5
New Lines = 3
Number of lower case characters in = 27
Number of upper case characters = 1
Number of digits = 6

-----------------------------------------------------------

You might also like