0% found this document useful (0 votes)
23 views10 pages

Python Programs for Common Tasks

The document contains a series of Python programming exercises covering various topics such as prime number checking, palindrome detection, finding largest/smallest numbers in lists, tuple swapping, storing student details in dictionaries, string manipulation, recursion for factorial and Fibonacci calculations, file handling, and random number generation. Each exercise includes a code snippet that demonstrates the solution to the problem. The document serves as a practical guide for implementing basic programming concepts in Python.

Uploaded by

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

Python Programs for Common Tasks

The document contains a series of Python programming exercises covering various topics such as prime number checking, palindrome detection, finding largest/smallest numbers in lists, tuple swapping, storing student details in dictionaries, string manipulation, recursion for factorial and Fibonacci calculations, file handling, and random number generation. Each exercise includes a code snippet that demonstrates the solution to the problem. The document serves as a practical guide for implementing basic programming concepts in Python.

Uploaded by

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

1.

Write a Program to show whether entered numbers are prime or not in


the given range.

Ans:

lower=int(input("Enter lowest number as lower bound to check : "))


upper=int(input("Enter highest number as upper bound to check: "))
c=0
for i in range(lower, upper+1):
if (i == 1):
continue

# flag variable to tell if i is prime or not


flag = 1

for j in range(2, i // 2 + 1):


if (i % j == 0):
flag = 0
break

# flag = 1 means i is prime


# and flag = 0 means i is not prime
if (flag == 1):
print(i, end = " ")

2. Input a string and determine whether it is a palindrome or not.

Ans:

string=input('Enter a string:')
length=len(string)
mid=length//2
rev=-1
for a in range(mid):
if string[a]==string[rev]:
print(string,'is a palindrome.')
break
else:
print(string,'is not a palindrome.')
3. Find the largest/smallest number in a list/tuple

Ans:
# creating empty list
list1 = []

# asking number of elements to put in list


num = int(input("Enter number of elements in list: "))

# iterating till num to append elements in list


for i in range(1, num + 1):
ele= int(input("Enter elements: "))
[Link](ele)

# print maximum element


print("Largest element is:", max(list1))

# print minimum element


print("Smallest element is:", min(list1))

4. WAP to input any two tuples and swap their values.

Ans:

t1 = tuple()
n = int (input("Total no of values in First tuple: "))
for i in range(n):
a = input("Enter Elements : ")
t1 = t1 + (a,)
t2 = tuple()
m = int (input("Total no of values in Second tuple: "))
for i in range(m):
a = input("Enter Elements : ")
t2 = t2 + (a,)
print("First Tuple : ")
print(t1)
print("Second Tuple : ")
print(t2)

t1,t2 = t2, t1

print("After Swapping: ")


print("First Tuple : ")
print(t1)
print("Second Tuple : ")
print(t2)

5. WAP to store students’ details like admission number, roll number,


name and percentage in a dictionary and display information on the basis
of admission number.

Ans:

record = dict ()
i=1
n= int (input ("How many records u want to enter: "))
while(i<=n):
Adm = input("Enter Admission number: ")
roll = input("Enter Roll Number: ")
name = input("Enter Name :")
perc = float(input("Enter Percentage : "))
t = (roll,name, perc)
record[Adm] = t
i=i+1
Nkey = [Link]()
for i in Nkey:
print("\nAdmno- ", i, " :")
r = record[i]
print("Roll No\t", "Name\t", "Percentage\t")
for j in r:
print(j, end = "\t")

6. Write a program with a user-defined function with string as a parameter


which replaces all vowels in the string with ‘*’.

Ans:

def strep(str):

# convert string into list

str_lst =list(str)

# Iterate list

for i in range(len(str_lst)):

# Each Character Check with Vowels


if str_lst[i] in 'aeiouAEIOU':

# Replace ith position vowel with'*'

str_lst[i]='*'

#to join the characters into a new string.

new_str = "".join(str_lst)
return new_str

def main():
line = input("Enter string: ")
print("Orginal String")
print(line)
print("After replacing Vowels with '*'")
print(strep(line))
main()

7. Recursively find the factorial of a natural number

Ans:

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

def main():
n = int(input("Enter any number: "))
print("The factorial of given number is: ",factorial(n))
main()

8. Write a recursive code to find the sum of all elements of a list.

Ans:
def lstSum(lst,n):
if n==0:
return 0
else:
return lst[n-1]+lstSum(lst,n-1)

mylst = [] # Empty List

#Loop to input in list

num = int(input("Enter how many number :"))


for i in range(num):
n = int(input("Enter Element "+str(i+1)+":"))
[Link](n) #Adding number to list
sum = lstSum(myl
st,len(mylst))
print("Sum of List items ",mylst, " is :",sum)

9. Write a recursive code to compute the nth Fibonacci number.

Ans:def fibonacci(n):
if n == 0:
return 0
elif n == 1:
return 1
else:
return(fibonacci(n-2) + fibonacci(n-1))

nterms = int(input("Please enter the Range Number: "))

# check if the number of terms is valid


if nterms <= 0:
print("Plese enter a positive integer")
else:
print("Fibonacci sequence:")
for i in range(nterms):
print(fibonacci(i),end=' ')

[Link] a text file line by line and display each word separated by a #.
Ans:

filein = open("[Link]",'r')
line =" "
while line:
line = [Link]()
#print(line)
for w in line:
if w == ' ':
print('#',end = '')
else:
print(w,end = '')
[Link]()

'''
#-------------OR------------------

filein = open("[Link]",'r')
for line in filein:
word= line .split()
for w in word:
print(w + '#',end ='')
print()
[Link]()

'''

11. Read a text file and display the number of vowels/ consonants/
uppercase/ lowercase characters and other than character and digit in the
file.

Ans:
filein = open("[Link]",'r')
line = [Link]()
count_vow = 0
count_con = 0
count_low = 0
count_up = 0
count_digit = 0
count_other = 0
print(line)
for ch in line:
if [Link]():
count_up +=1
if [Link]():
count_low += 1
if ch in 'aeiouAEIOU':
count_vow += 1
if [Link]():
count_con += 1
if [Link]():
count_digit += 1
if not [Link]() and ch !=' ' and ch !='\n':
count_other += 1

print("Digits",count_digit)
print("Vowels: ",count_vow)
print("Consonants: ",count_con-count_vow)
print("Upper Case: ",count_up)
print("Lower Case: ",count_low)
print("other than letters and digit: ",count_other)

[Link]()

12. Write a Python code to find the size of the file in bytes, the number of
lines, number of words and no. of character.

Ans:

import os
lines = 0
words = 0
letters = 0
filesize = 0

for line in open("[Link]"):


lines += 1
letters += len(line)
# get the size of file
filesize = [Link]("[Link]")

# A flag that signals the location outside the word.


pos = 'out'
for letter in line:
if letter != ' ' and pos == 'out':
words += 1
pos = 'in'
elif letter == ' ':
pos = 'out'

print("Size of File is",filesize,'bytes')


print("Lines:", lines)
print("Words:", words)
print("Letters:", letters)

13. Write a program that accepts a filename of a text file and reports the
file's longest line.

Ans:

def get_longest_line(filename):
large_line = ''
large_line_len = 0
with open(filename, 'r') as f:
for line in f:
if len(line) > large_line_len:
large_line_len = len(line)
large_line = line

return large_line

filename = input('Enter text file Name: ')


print (get_longest_line(filename+".txt"))

14. Write a random number generator that generates random numbers


between 1 and 6 (simulates a dice).

Ans:

import random
import random

def roll_dice():
print ([Link](1, 6))

print("""Welcome to my python random dice program!


To start press enter! Whenever you are over, type quit.""")

flag = True
while flag:
user_prompt = input(">")
if user_prompt.lower() == "quit":
flag = False
else:
print("Rolling dice...\nYour number is:")
roll_dice()

15. Take a sample of ten phishing e-mails (or any text file) and find the
most commonly occurring word(s).

Ans:

def Read_Email_File():
import collections
fin = open('[Link]','r')
a= [Link]()
d={ }
L=[Link]().split()
for word in L:
word = [Link](".","")
word = [Link](",","")
word = [Link](":","")
word = [Link]("\"","")
word = [Link]("!","")
word = [Link]("&","")
word = [Link]("*","")
for k in L:
key=k
if key not in d:
count=[Link](key)
d[key]=count
n = int(input("How many most common words to print: "))
print("\nOK. The {} most common words are as follows\n".format(n))
word_counter = [Link](d)
for word, count in word_counter.most_common(n):
print(word, ": ", count)
[Link]()

#Driver Code
def main():
Read_Email_File()
main()

You might also like