Python Programs
Python Programs
II. Start the Python interpreter and type help() to start the online help utility.
Solution :
To install Python in windows, we have to download Python software pack from official
website of Python Software Foundation.
1. Go to [Link]
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
Python Documentaion:
3. Select version
4. Select topic
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
In this tutorial we are going to install Python 3 on Linux (Ubuntu) Operating System.
To install Python 3
3. To check if python is install properlyor not, we will check the version of python
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
>>> help()
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
>>> a = 10
>>> b = 30
>>> 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 ( 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 ( 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 ( 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 :
>>> 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 ( 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 ( 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 :
Where,
A is amount,
P is the principal amount
R is the rate of interest,
T is the time span
PROGRAM: ([Link])
OUTPUT:
-------------------------------------------------------------------------------------------------------------
4. Read the name, address, email and phone number of a person through the
keyboard and print the details.
Solution :
PROGRAM: ([Link])
OUTPUT:
-------------------------------------------------------------------
5
44
333
2222
11111
Solution :
PROGRAM: ([Link])
OUTPUT:
Enter no of rows = 5
5
44
333
2222
11111
-------------------------------------------------------------
Solution :
PROGRAM: (check_input_char.py)
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)
OUTPUT:
-------------------------------------------------------------------
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]]
--------------------------------------------------------
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 :
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:
--------------------------------------------------------
[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:
-------------------------------------------------------------------
[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]
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:
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
---------------------------------------------------------
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:
---------------------------------------------------------
[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
OUTPUT:
---------------------------------------------
[Link] a recursive function that generates all binary strings of n-bit length.
Solution :
PROGRAM: (binary_strings.py)
OUTPUT:
-------------------------------------------------------------------
[Link] a python program that defines a matrix and prints.
Solution :
PROGRAM: (matrix_print.py)
OUTPUT:
123
456
789
--------------------------------------------------
Solution :
To Install in Windows:
pip install numpy
To Install in Linux:
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:
----------------------------------------------------
Solution :
PROGRAM: ([Link])
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 = "))
OUTPUT:
---------------------------------------------------
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)
OUTPUT:
----------------------------------------------
[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 :
OUTPUT:
Solution :
PROGRAM: (draw_point.py)
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)
OUTPUT:
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:
Solution :
This is Study Glance. Study Galnce provides various Study related meterials.
PROGRAM: (most_word.py)
count = 0
word = " "
max_Count = 0
words = []
OUTPUT:
---------------------------------------------------------------
[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 :
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:
-----------------------------------------------------------