0% found this document useful (0 votes)
3 views34 pages

Python Programs

The document contains a series of programming tasks with code examples in Python, covering various topics such as calculating age, volume of a cone, distance between points, string analysis, series summation, and working with lists and dictionaries. Each task is presented with a brief description and corresponding code snippets. The tasks demonstrate fundamental programming concepts and operations using Python.

Uploaded by

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

Python Programs

The document contains a series of programming tasks with code examples in Python, covering various topics such as calculating age, volume of a cone, distance between points, string analysis, series summation, and working with lists and dictionaries. Each task is presented with a brief description and corresponding code snippets. The tasks demonstrate fundamental programming concepts and operations using Python.

Uploaded by

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

Roll No: 223R1A0466

TASK – 1

A) Write a program Read your name and age to display the year in which
you will turn 100 years old.

Program Code:

name = input ("Enter the Name: ")


age = int (input("Enter the Age: "))
# Let present year is 2021
userage = (100 - age) + 2021
print (f " {name} will become 100 years old in the year {userage}")
Roll No: 223R1A0466

B) Write a program to Read radius and height of a cone and to find the
volume of a cone.

Formula : Surface Area of a cone = πr (r+√h² + r²)

Program Code:
# importing math to use sqrt() function

import math

# Reading radius

radius = float(input("Enter radius of cone: "))

# Reading height

height = float(input("Enter height of cone: "))

# Calculating surface area of cone

area = 3.141592 * radius * (radius + [Link](radius*radius + height*height))

# Displaying area

print("Surface area = ", area)


Roll No: 223R1A0466

C) Write a program to compute distance between two points taking input


from the user (Hint: use Pythagorean theorem)

Formula: d=√((x_2-x_1)²+(y_2-y_1)²)

Program Code:
#To find the Distance between Two Points
import math
x1 = int(input("Enter the first coordinate of first point: "))
y1 = int(input("Enter the second coordinate of first point: "))
x2 = int(input("Enter the first coordinate of second point: " ))
y2 = int(input("Enter the second coordinate of second point: " ))
#Distance between two points (D = sqrt((x2-x1)^2 + (y2-y1)^2))
distance = [Link]((x2 - x1) ** 2 + (y2 - y1) ** 2)
print("Distance between two points is: ",distance)
Roll No: 223R1A0466

TASK – 2

A) Write a program to Read your email id and display the no of vowels,


consonants, digits and special symbols in it using if…elif…else statement

Program code:

vcount = 0
ccount = 0
digcount=0
spcount=0
str = input(“Enter the your email id: “)
#Converting entire string to lower case to reduce the comparisons
str = [Link]()
for i in range(0,len(str)):
#Checks whether a character is a vowel
if str[i] in ('a', 'e', 'i', 'o', 'u'):
vcount = vcount + 1
elif (str[i] >= 'a' and str[i] <= 'z'):
ccount = ccount + 1

elif(str[i]>=’0’ and str[i]<=’9’):

digcount=digcount+1

else:

spcount=spcount+1

print("Total number of Vowels : ",vcount )


print("Total number of Consonants : ",ccount )
print("Total number of Digits : ",digcount )
print("Total number of Special characters : ",spcount )
Roll No: 223R1A0466

B) Write a Program to find the sum of a Series


1/1! + 2/2! + 3/3! + 4/4! +…….+ n/n!. (Input :n = 5, Output : 2.70833)

Program code:

import math

n=int(input("Enter the number of terms: "))

sum=0

for i in range(1,n+1):

sum=sum+(i/[Link](i))

print("The sum of series is",round(sum,2))


Roll No: 223R1A0466

C) In number theory, an abundant number or excessive number is a number for


which the sum of its proper divisors is greater than the number itself. Write a
program to find out, if the given number is abundant. (Input: 12, Sum of divisors of
12 = 1 + 2 + 3 + 4 + 6 = 16, sum of divisors 16 > original number 12)

Program code:

num = int(input("Enter a number : "))


total = 0
abundant= 0
for i in range(1,num):
if(num % i == 0):
total = total + i
if(total > num):
print("It is an abundant number.")

else :

print("It is not an abundant number.")


Roll No: 223R1A0466

TASK - 3

A) Read a list of numbers and write a program to check whether a particular


element is present or not using membership operators

Program code:

# creating a list
list = [2, 5, 7, 8, 10, 12, 15, 18, 20 ]
num = int (input("Enter any number :"))

if num in list:
print(f"The given number {num} is to found in the list")
else:
print(f"The given number {num} is to not found in the list")
Roll No: 223R1A0466

B) Read a list of numbers and print the numbers divisible by x but not by y
(Assume x = 4 and y = 5).

Program code:
# creating an empty list
lst = []

# number of elements as input


n = int(input("Enter number of elements : "))

# iterating till the range


for i in range(0, n):
ele = int(input())
[Link](ele) # adding the element

print("Display List of elements :",lst)

x = int(input("Enter the x value:"))


y = int(input("Enter the y value:"))
print("Display list of numbers divisible by x but not by y")
for i in lst:
if i%x==0 and i%y!=0:
print(i)
Roll No: 223R1A0466

C) Read a list of numbers and print the sum of odd integers and even integers
from the list
(Ex: [23, 10, 15, 14, 63], odd numbers sum = 101, even numbers sum = 24)

Program code:

# creating an empty list


lst = []

# number of elements as input


n = int(input("Enter number of elements : "))

# iterating till the range


for i in range(0, n):
ele = int(input())
[Link](ele) # adding the element

print("Display List of elements :",lst)

esum=0
osum=0

for i in lst:
if i%2==0:
esum=esum+i
else:
osum=osum+i

print("List of elements even sum value :",esum)


print("List of elements odd sum value :",osum)
Roll No: 223R1A0466

D) Read a list of numbers and print numbers present in odd index position

Program:

# creating an empty list


lst = []

# number of elements as input


n = int(input("Enter number of elements : "))

# iterating till the range


for i in range(0, n):
ele = int(input())
[Link](ele) # adding the element

print("Display List of elements :",lst)


print("Display Odd index position values")

for i in range(0,len(lst)):
if i%2!=0:
print(f"index {i} position value = {lst[i]}")
Roll No: 223R1A0466

E) Read a list of numbers and remove the duplicate numbers from it.
(Ex: Enter a list with duplicate elements: 10 20 40 10 50 30 20 10 80,
The unique list is: [10, 20, 30, 40, 50, 80])

Program code:

# creating an empty list


lst = []

# number of elements as input


n = int(input("Enter number of elements : "))

# iterating till the range


for i in range(0, n):
ele = int(input())
[Link](ele) # adding the element

print("Display List of elements :",lst)

templist = []
for i in lst:
if i not in templist:
[Link](i)

lst = templist
print("Display List After removing duplicates : ",lst)
Roll No: 223R1A0466

TASK - 4

A) Given a list of tuples. Write a program to find tuples which have all
elements divisible by K from a list of tuples.
test_list = [(6, 24, 12), (60, 12, 6), (12, 18, 21)], K = 6,
Output : [(6, 24, 12), (60, 12, 6)]

Program code:
# initializing list
test_list = [(6, 24, 12), (60, 12, 6), (12, 18, 21)]

# printing original list


print("The original list is : ",test_list)

# initializing K
K=6

# all() used to filter elements


res = [sub for sub in test_list if all(ele % K == 0 for ele in sub)]

# printing result
print(f"{K} Divisible by Multiple elements list of tuples : ",res)
Roll No: 223R1A0466

B) Given a list of tuples. Write a program to filter all uppercase characters


tuples from given list of tuples.
(Input: test_list = [(“GFG”, “IS”, “BEST”), (“GFg”, “AVERAGE”),
(“GfG”, ), (“Gfg”, “CS”)],
Output : [(„GFG‟, „IS‟, „BEST‟)]).

Program code:

# initializing list
test_list = [("GFG", "IS", "BEST"), ("GFg", "AVERAGE"), ("GfG", ), ("Gfg", "CS")]

# printing original list


print("The original list is : ",test_list)

# all() returns true only when all strings are uppercase


res = [sub for sub in test_list if all([Link]() for ele in sub)]

# printing results
print("Filtered all uppercase characters list of Tuples : ", res)
Roll No: 223R1A0466

C) Given a tuple and a list as input, write a program to count the occurrences
of all items of the list in the tuple.
(Input : tuple = ('a', 'a', 'c', 'b', 'd'), list = ['a', 'b'], Output : 3)
Program code:

tup = ('a', 'a', 'c', 'b', 'd')


lst = ['a', 'b']

print("Tuple values = ",tup)


print("List values = ",lst)

count = 0
for item in tup:
if item in lst:
count+= 1

print("The occurrences of all items of the list in the tuple count value = ",count)
Roll No: 223R1A0466

TASK-5

A) Write a program to generate and print a dictionary that contains a number


(between 1 and n) in the form (x, x*x).
Program code:

n=int(input("Input a number "))


d = dict()

for x in range(1,n+1):
d[x]=x*x

print(d)
Roll No: 223R1A0466

B) Write a program to perform union, intersection and difference using


Set A and Set B.

Program code:
# sets are define
A = {0, 2, 4, 6, 8};
B = {1, 2, 3, 4, 5};

# union
print("Union :", A | B)

# intersection
print("Intersection :", A & B)

# difference
print("Difference :", A - B)

# symmetric difference
print("Symmetric difference :", A ^ B)
Roll No: 223R1A0466

C) Write a program to count number of vowels using sets in given string


(Input : “Hello World”, Output: No. of vowels : 3)

Program code:

s=input("Enter string:")

count = 0

vowels = set("aeiou")

for letter in s:

if letter in vowels:

count += 1

print("Count of the vowels is:",count)


Roll No: 223R1A0466

D) Write a program to form concatenated string by taking uncommon


characters from two strings using set concept (Input : S1 = "aacdb",
S2 = "gafd", Output : "cbgf").

Program code:

str1=input("Enter First string:")


str2=input("Enter Second string:")
print("First string = ",str1)
print("Second string = ",str2)
s1 = set(str1)
print("First string set values = ",s1)
s2 = set(str2)
print("Second string set values = ",s2)
dif = s1.symmetric_difference(s2)
print("Set concept using from two strings uncommon characters = ",dif)
Roll No: 223R1A0466

TASK-6

A) Write a program to do the following operations:


i. Create a empty dictionary with dict() method
ii. Add elements one at a time
iii. Update existing key‟s value
iv. Access an element using a key and also get() method
v. Deleting a key value using del() method

Program Code:
#Create a empty dictionary with dict() method
dictvar = dict()
print("Display empty dictionary")
print(dictvar)
#Add elements one at a time
dictvar['Name'] = 'Pawan'
dictvar['Age'] = 20
dictvar['Address']='Kavali'
print("Display after adding dictionary values")
print(dictvar)
#Update existing key's value
dictvar['Address']='Nellore'
print("Display after Update dictionary values")
print(dictvar
#Access an element using a key and also get() method
print("Display Name key value : ",[Link]('Name'))
#Deleting a key value using del() method
del dictvar['Age']
print("Display after delete dictionary values")
print(dictvar)
Roll No: 223R1A0466

B. Write a program to create a dictionary and apply the following methods:


i. pop() method
ii. popitem() method
iii. clear() method

Program Code:
#Create a dictionary
branchcode = {'CIVIL':101, 'EEE':201, 'ME':301, 'ECE':401, 'CSE':501}
print("Display dictionary values")
print(branchcode)
#Apply the pop() method delete a specific element
[Link]('ME')
print("Display dictionary values after apply pop() method")
print(branchcode)
#Apply the popitem() method delete a random element
[Link]()
print("Display dictionary values after apply popitem() method")
print(branchcode)
#Apply the clear() method delete all element from the dictionary
[Link]()
print("Display dictionary values after apply clear() method")
print(branchcode)
Roll No: 223R1A0466

C) Given a dictionary, write a program to find the sum of all items in the
dictionary.

Program Code:

#Create a dictionary
branchcode = {'CIVIL':101, 'EEE':201, 'ME':301, 'ECE':401, 'CSE':501}
print("Display dictionary values")
print(branchcode)
#From the dictionary to separate values
codeval = [Link]()
print("Display them to separate values from the Dictionary")
print(codeval)
sum = 0
for i in codeval:
sum = sum + i
print("In the dictionary to display sum of all items value : ",sum)
Roll No: 223R1A0466

D) Write a program to merge two dictionaries using update() method.

Program code:

# initializing the dictionaries


fruits = {"Apple": 2, "Orange" : 3, "Banana": 5}
print("Display fruits dictionary values")
print(fruits)
dry_fruits = {"Cashew": 3, "Almond": 4, "Pista": 6}
print("Display dry_fruits dictionary values")
print(dry_fruits)
# updating the fruits dictionary
[Link](dry_fruits)
# printing the fruits dictionary, it contains both the key: value pairs
print("Display dictionary values after merge two dictionaries")
print(fruits)
Roll No: 223R1A0466

TASK-7

A) Given a string, write a program to check if the string is symmetrical or not

Program code:

str = input("Enter the any String:")


n=len(str)
flag=0
if n%2:
mid=n//2+1
else:
mid= n//2
start=0
end= mid
while(start <mid and end<n):
if(str[start]== str[end]):
start= start+1
end= end+1
else:
flag=1
break
if flag==0:
print(f"The given string {str} is symmetrical")
else:
print(f"The given string {str} is not symmetrical")
Roll No: 223R1A0466

B) Given a string, write a program to check if the string is Polindrome or not

Program code:

str = input("Enter the any String:")


mid=(len(str)-1)//2
start=0
last= len(str)-1
flog =0
while(start <mid ):
if(str[start]== str[last]):
start = start+1
last = last-1
else:
flag=1
break
if flag==0:
print(f"The given string {str} Palindrome")
else:
print(f"The given string {str} is not Palindrome"
Roll No: 223R1A0466

C) Write a program to read a string and count the number of vowel letters
and print all letters except 'e' and 's'.

Program code:

str = input("Enter any string : ")

#Converting entire string to lower case to reduce the comparisons

str = [Link]();

vcount=0

print(f"The string {str} all characters diplay, except 'e' and 's' characters:")

for i in range(0,len(str)):

#Checks whether a character is a vowel

if str[i] in ('a','e','i','o','u'):

vcount = vcount + 1;

if str[i] in ('e','s'):

continue

else:

print(str[i])

print(f"Display {str} string total number of vowels : ",vcount)


Roll No: 223R1A0466

D) Write a program to read a line of text and remove the initial word from
given text. (Hint: Use split() method, Input : India is my country.
Output : is my country)

Program code:

str = input("Enter the one line string : ")

# printing original string


print("The original string is : ",str)

# Using split()
# Removing Initial word from string
res = [Link](' ', 1)[1]

# printing result
print("The string after removing first word : ",res)
Roll No: 223R1A0466

E) Write a program to read a string and count how many times each letter
appears. (Histogram).

Program code:

text = input("Enter the any String: ")


result = {}
print(f"Display count each character appear in {text} string ")
# Go through each letter in the text
for letter in text:
if letter not in result:
result[[Link]()] = 1
else:
result[[Link]()] += 1
print(result)
Roll No: 223R1A0466

TASK-8
A) A generator is a function that produces a sequence of results instead of a
single value. Write a generator function for Fibonacci numbers up to n

Program Code:

def fibonacci(num):
a=0
b=1
print("Display Fibonacci series values")
print(a)
print(b)
for i in range(3,num+1):
c=a+b
print(c)
a=b
b=c

num = int(input("Enter the how much fibonacci series generator value : "))
fibonacci(num)
Roll No: 223R1A0466

B) Write a fact() function to compute the factorial of a given positive number.

Program Code:

def fact(n):
if n == 0:
return 1
else:
return n * fact(n-1)

n=int(input("Enter a number to compute the factiorial : "))


print(f"{n}! factorial value = ",fact(n))
Roll No: 223R1A0466

C) Given a list of n elements, write a linear_search() function to search a given


element x in a list.

Program Code:
#To define Linearsearch function
def linearsearch(ls,x):
for i in range(0, len(ls)):
if (ls[i] == x):
return i
return -1

# creating an empty list


lst = []
n = int(input("Enter how many elements in the list: "))
print(f"Enter the {n} elements in the list: ")
for i in range(0, n):
ele = int(input())
[Link](ele) # adding the element
print("Display List of elements :",lst)
key = int(input("Enter the search key value: "))
result = linearsearch(lst, key)
if(result == -1):
print(f"Element {key} not found in the list")
else:
print(f"Element {key} found in the list at index position: ", result)
Roll No: 223R1A0466

TASK-9

A) Write a program to demonstrate the working of built-in statistical


functions mean(), mode(), median() by importing statistics library.

Program Code:
import statistics
# creating an empty list
lst = []
n = int(input("Enter how many elements in the list: "))
print(f"Enter the {n} elements in the list: ")
for i in range(0, n):
ele = int(input())
[Link](ele) # adding the element
print("Display List of elements :",lst)

#The mean() method calculates the arithmetic mean of the numbers in a list.
mean_value = [Link](lst)
print("Statistics mean value = ",mean_value)

#The mode() method returns the most common data point in the list.
mode_value = [Link](lst)
print("Statistics mode value = ",mode_value)

#The median() method returns the middle value of numeric data in a list.
median_value = [Link](lst)
print("Statistics median value = ",median_value)
Roll No: 223R1A0466

B) Write a program to demonstrate the working of built-in trignometric


functions sin(), cos(), tan(), hypot(), degrees(), radians() by importing math
module.

Program Code:
import math

r = int(input("Enter the radians value: "))


x = int(input("Enter the x value: "))
y = int(input("Enter the y value: "))

#It returns the sine of the number (in radians).


print(f"sin({r}) value = ",[Link](r))

#It returns the cos of the number (in radians).


print(f"cos({r}) value = ",[Link](r))

#It returns the tangent of the number (in radians).


print(f"tan({r}) value = ",[Link](r))

#hypot it returns the distance between origin and the points (x,y)
print(f"hypot({x},{y}) value = ",[Link](x,y))

# It used to convert the angle x from radians into degrees


print(f"degrees({r}) value = ",[Link](r))

# It used to convert the angle x from degrees into radians


print(f"radians({r}) value = ",[Link](r))
Roll No: 223R1A0466

C) Write a program to demonstrate the working of built-in Logarithmic and


Power functions exp(), log(), log2(), log10(), pow() by importing math module.

Program Code:
import math

x = int(input("Enter the x value: "))


y = int(input("Enter the y value: "))

# It returns the value of e raised to the power a (e**a)


print(f"exp({x}) value = ",[Link](x))

# It returns the logarithm of the specified number with respect to the base e
print(f"log({x}) value = ",[Link](x))

# It returns the logarithm of the specified number with respect to the base 2
print(f"log2({x}) value = ",math.log2(x))

# It returns the logarithm of the specified number with respect to the base 10
print(f"log10({x}) value = ",math.log10(x))

# It returns the value of x raised to power y.


print(f"pow({x,y}) value = ",[Link](x,y))
Roll No: 223R1A0466

D) Write a program to demonstrate the working of built-in numeric functions


ceil(), floor(), fabs(), factorial(), gcd() by importing math module.

Program Code:
import math

num1 = float(input("Enter the floating point value:"))

# It returns the number is rounded up to its next integer value.


print(f"ceil({num1}) value = ",[Link](num1))

# It returns the floor value of the number rounded down to the previous integer value
print(f"floor({num1}) value = ",[Link](num1))

num2 = float(input("Enter the negative value:"))


# It returns the absolute value of the number, i.e removes the negative(-) sign
print(f"fabs({num2}) value = ",[Link](num2))

num3 = int(input("Enter the factorial value:"))


#It returns the factorial of x.
print(f"factorial({num3}) value = ",[Link](num3))

x = int(input("Enter the x value:"))


y = int(input("Enter the y value:"))
#It returns the greatest common divisor of the two integers x and y
print(f"gcd({x,y}) value = ",[Link](x,y))

You might also like