Pyhton Practicals PDF

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 17

Programming using

python

PYTHON Mehak Gupta


CSC/22/18
PRACTICALS
Semester-I ; DSC:1
1. WAP to find the roots of a quadratic equation.
import cmath

equation = input("Enter the quadratic equation: ")

a = float(input('Enter a: '))

b = float(input('Enter b: '))

c = float(input('Enter c: '))

# calculate the discriminant

d = (b**2) - (4*a*c)

sol_1 = (-b-cmath.sqrt(d))/(2*a)

sol_2 = (-b+cmath.sqrt(d))/(2*a)

print('The solutions of given quadratic equation',equation,' are: ',sol_1,sol_2)

Output:

2. WAP to accept a number ‘n’ and create 3 functions as follows:


a. Check if ’n’ is prime
b. Generate all prime numbers till ‘n’
c. Generate first ‘n’ prime numbers
n = int(input("Enter the number: "))

def Prime_number(n):

flag = False

if n == 1:

print(n, "is not a prime number")

elif n > 1:

for i in range(2, n):

if (n % i) == 0:

flag = True

break

if flag:

print(n, "is not a prime number")


else:

print(n, "is a prime number")

Prime_number(n)

def Generate_prime_number(n):

print("All Prime numbers till {} are: ".format(n), end='')

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

if n > 1:

for i in range(2, n):

if (n % i) == 0:

break

else:

print(n, end=' ')

Generate_prime_number(n)

print()

def first_n_prime_number(n):

print("First {} Prime numbers are: ".format(n), end='')

count = 0

n1 = 2

while True:

is_prime = True

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

if n1%i == 0:

is_prime = False

break

if is_prime == True:

print(n1, end=' ')

count+=1

if count == n:

break

n1+=1

first_n_prime_number(n)

Output:
3. WAP to create a pyramid of the character ‘*’ and also reverse pyramid.
n = int(input("Enter the number of lines you want to print: "))

for i in range(n):

for j in range(i,n):

print(end= ' ')

for j in range(i+1):

print('* ', end= '')

print('')

print()

for i in range(n):

for j in range(i+1):

print(end= ' ')

for j in range(i,n):

print('* ', end= '')

print('')

Output:

4. WAP that accepts a character and performs the following:


a. print whether the character is a letter or numeric digit or a special character
b. if the character is a letter, print whether the letter is uppercase or lowercase
c. if the character is a numeric digit, prints its name in text (e.g., if input is 9, output is
NINE)
def main():

ch = input("Enter any character: ")

check_character(ch)

def check_character(ch):

if(ch.isalpha()):

print("The given character", ch, "is an Alphabet")

lowercase_uppercase(ch)

elif(ch.isdigit()):

print("The given character", ch, "is a Digit")

digit_text(ch)

else:

print("The given character", ch, "is a Special Character")

def lowercase_uppercase(ch):

if(ch.islower()):

print("The given character", ch, "is Lowercase")

elif(ch.isupper()):

print("The given character", ch, "is Uppercase")

def digit_text(ch):

L1 = ['1','2','3','4','5','6','7','8','9']

L2 = ['ONE','TWO','THREE','FOUR','FIVE','SIX','SEVEN','EIGHT','NINE']

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

if(L1[i]==ch):

print(L2[i])

if __name__=="__main__":

main()

Output:

5. WAP to perform the following operations on a string


a. Find the frequency of a character in a string.
b. Replace a character by another character in a string.
c. Remove the first occurrence of a character from a string.
d. Remove all occurrences of a character from a string.
def main():

str1 = input("Enter the string: ")

frequency(str1)

replace(str1)

remove_first_occurrence(str1)

remove_all_occurrences(str1)

def frequency(str1):

ch = input("Enter a character to check it's frequency in given string: ")

freq = str1.count(ch)

print("The frequency of a character", ch, "in a string is: ",freq)

def replace(str1):

o = input("Enter a character you want to replace: ")

n = input("Enter a character to replace old character with: ")

new_str = str1.replace(o,n)

print("The new string with replaced character is: ",new_str)

def remove_first_occurrence(str1):

ch_remove = input("Enter a character you want remove first occurrenece of: ")

x = str1.find(ch_remove)

str2 = str1[:x]+str1[x+1::]

print("String after removing first occurrence: ",str2)

def remove_all_occurrences(str1):

ch_remove = input("Enter a character you want remove all occurreneces of: ")

print("String after removing all occurrence: ", end='')

str1 = list(str1)

for i in range(len(str1)):

if str1[i] != ch_remove:

print(str1[i], end='')

if __name__=="__main__":

main()

Output:
6. WAP to swap the first 'n' characters of two strings.
str1 = input("Enter the first string: ")

str2 = input("Enter the seconf string: ")

n = int(input("Enter the number of characters you want to swap: "))

x = str1[:n]

str1 = str1.replace(str1[:n],str2[:n])

str2 = str2.replace(str2[:n],x)

print("First string after swapping",n, "characters from second string: ",str1)

print("Second string after swapping",n, "characters from first string: ",str2)

Output:

7. Write a function that accepts two strings and returns the indices of all the occurrences
of the second string in the first string as a list. If the second string is not present in the
first string then it should return -1.
def main():

str1 = input("Enter the first string: ")

str2 = input("Enter the second string: ")

character_occurrence(str1,str2)

def character_occurrence(str1,str2):

l1 = []

flag = False

for i in range(len(str1)):
if (str1[i:i + len(str2)] == str2):

l1.append(i)

flag = True

if l1:

print("The indices of all the occurrences of the second string in the first
string are: ",l1)

else:

print(-1)

if __name__=="__main__":

main()

Output:

8. WAP to create a list of the cubes of only the even integers appearing in the input list
(may have elements of other types also) using the following:
a. 'for' loop
b. list comprehension
L1 = []

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

for i in range(0, n):

element = int(input())

L1.append(element)

#a.

L2 = []

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

if (L1[i]%2==0):

L2.append(pow(L1[i], 3))

print(L2)

#b.

L2 = [pow(number,3) for number in L1 if number%2==0]

print(L2)
Output:

9. WAP to read a file


a. Print the total number of characters, words and lines in the file.
b. Calculate the frequency of each character in the file. Use a variable of dictionary type
to maintain the count.
c. Print the words in reverse order.
d. Copy even lines of the file to a file named ‘File1’ and odd lines to another file named
‘File2’.
myfile = open("Poem.txt","r")

f1 = myfile.read()

print("The total number of characters in the file are: ",len(f1))

words = f1.split( )

print("The total number of words in the file are: ",len(words))

myfile.seek(0)

lines = myfile.readlines()

print("The total number of lines in the file are: ",len(lines))

myfile.seek(0)

test_str = myfile.read().lower()

dicx = {}

for i in test_str:

if i in dicx:

dicx[i] += 1

else:

dicx[i] = 1

print(dicx)
reverse = f1[::-1]

print(reverse)

f2 = open("even.txt","w")

f3 = open("odd.txt","w")

for i in range(len(lines)):

if(i%2 == 0):

f2.write(lines[i])

else:

f3.write(lines[i])

f2.close()

f3.close()

myfile.close()

Output:

10. WAP to define a class Point with coordinates x and y as attributes. Create relevant
methods and print the objects. Also define a method distance to calculate the distance
between any two points objects.
import math

class Point:

def __init__(self, x, y):


self.x = x

self.y = y

print("Point({}, {})".format(self.x, self.y))

def distance(self, other_point):

x_diff = (self.x - other_point.x) ** 2

y_diff = (self.y - other_point.y) ** 2

return math.sqrt(x_diff + y_diff)

x1 = int(input("Enter x1: "))

y1 = int(input("Enter y1: "))

x2 = int(input("Enter x2: "))

y2 = int(input("Enter y2: "))

point1 = Point(x1, y1)

point2 = Point(x2, y2)

print(point1.distance(point2))

Output:

11. Write a function that prints a dictionary where the keys are numbers between 1 and 5
and the values are cubes of the keys.
def cube():

d = dict()

for x in range(1,6):

d[x] = x**3

return d

print(cube())

Output:
12. Consider a tuple t1= (1, 2, 5, 7, 9, 2, 4, 6, 8, 10). WAP to perform following operations:
a. Print half the values of the tuple in one line and the other half in the next line.
b. Print another tuple whose values are even numbers in the given tuple.
c. Concatenate a tuple t2 = (11,13,15) with t1.
d. Return maximum and minimum value from this tuple
t1 = (1, 2, 5, 7, 9, 2, 4, 6, 8, 10)

first_half = t1[:int(len(t1)/2)]

second_half = t1[int(len(t1)/2):]

print("The first half values of the tuple are: ",first_half)

print("The other half values of the tuple are: ",second_half)

l1 = list()

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

if t1[i]%2==0:

l1.append(t1[i])

print("Even numbers in the given tuple are: ",tuple(l1))

t2 = (11,13,15)

t3 = t1+t2

print("Concatenated tuple t3 is: ",t3)

print("Maximum value from t3 is: ",max(t3))

print("Minimum value from t4 is: ",min(t3))

Output:

13. WAP to accept a name from a user. Raise and handle appropriate exception(s) if the
text entered by the user contains digits and/or special characters.
import re

def validate_name(name):

pattern = re.compile("^[a-zA-Z]+$")

if not pattern.match(name):

raise ValueError("Name can only contain letters")

return name
try:

name = input("Enter your name: ")

name = validate_name(name)

print("Hello, {}!".format(name))

except ValueError as ve:

print("Error: ", ve)

Output:

14. WAP to return the percentage of the marks obtained by a student using assert
statement.
def get_percentage(marks, total_marks):

assert 0 <= marks <= total_marks, "Invalid marks"

return (marks / total_marks) * 100

try:

marks = float(input("Enter marks obtained: "))

total_marks = float(input("Enter total marks: "))

percentage = get_percentage(marks, total_marks)

print("Percentage: {:.2f}%".format(percentage))

except AssertionError as ae:

print("Error:", ae)

except ValueError as ve:

print("Error: Invalid input. Enter a number.")

Output:
15. WAP to return the grade of the student according to his marks.
marks = float(input("Enter marks obtained: "))

if marks>=90:

print("Grade: A1")

elif 80<=marks<90:

print("Grade: A2")

elif 70<=marks<80:

print("Grade: B1")

elif 60<=marks<70:

print("Grade: B2")

elif 50<=marks<60:

print("Grade: C1")

elif 40<=marks<50:

print("Grade: C2")

elif 33<=marks<40:

print("Grade: D")

else:

print("Grade: E(Fail)")

Output:
16. WAP to print the factorial of a number using factorial function.
import math

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

f = math.factorial(num)

print("Factorial of", num, "is: ",f)

Output:

17. WAP to print the factors of a number.


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

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

if (n % i) == 0:

print(i,end=" ")

Output:

18. WAP to print the HCF of two numbers.


num_1 = int(input("Enter the first number: "))

num_2 = int(input("Enter the second number: "))

if num_1 > num_2:


smaller = num_2

else:

smaller = num_1

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

if((num_1 % i == 0) and (num_2 % i == 0)):

hcf = i

print("The H.C.F. is: ",hcf)

Output:

19. WAP to find the lcm of two numbers.


num_1 = int(input("Enter the first number: "))

num_2 = int(input("Enter the second number: "))

if num_1>num_2:

greater = num_1

else:

greater = num_2

while(True):

if((greater % num_1 == 0) and (greater % num_2 == 0)):

lcm = greater

break

greater += 1

print("The L.C.M. is: ",lcm)

Output:

20. WAP to interchange the two numbers stored in two variables using another variable.
x = int(input("Enter the first number: "))

y = int(input("Enter the second number: "))

temp = x

x = y

y = temp

print('The value of x after swapping: ',x)

print('The value of y after swapping: ',y)

Output:

21. WAP to interchange the two numbers stored in two variables without using another
variable
x = int(input("Enter the first number: "))

y = int(input("Enter the second number: "))

x,y=y,x

print('The value of x after swapping: ',x)

print('The value of y after swapping: ',y)

Output:

--------------- END -----------------

You might also like