Pyhton Practicals PDF
Pyhton Practicals PDF
Pyhton Practicals PDF
python
a = float(input('Enter a: '))
b = float(input('Enter b: '))
c = float(input('Enter c: '))
d = (b**2) - (4*a*c)
sol_1 = (-b-cmath.sqrt(d))/(2*a)
sol_2 = (-b+cmath.sqrt(d))/(2*a)
Output:
def Prime_number(n):
flag = False
if n == 1:
elif n > 1:
if (n % i) == 0:
flag = True
break
if flag:
Prime_number(n)
def Generate_prime_number(n):
if n > 1:
if (n % i) == 0:
break
else:
Generate_prime_number(n)
print()
def first_n_prime_number(n):
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:
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):
for j in range(i+1):
print('')
print()
for i in range(n):
for j in range(i+1):
for j in range(i,n):
print('')
Output:
check_character(ch)
def check_character(ch):
if(ch.isalpha()):
lowercase_uppercase(ch)
elif(ch.isdigit()):
digit_text(ch)
else:
def lowercase_uppercase(ch):
if(ch.islower()):
elif(ch.isupper()):
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:
frequency(str1)
replace(str1)
remove_first_occurrence(str1)
remove_all_occurrences(str1)
def frequency(str1):
freq = str1.count(ch)
def replace(str1):
new_str = str1.replace(o,n)
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::]
def remove_all_occurrences(str1):
ch_remove = input("Enter a character you want remove all occurreneces of: ")
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: ")
x = str1[:n]
str1 = str1.replace(str1[:n],str2[:n])
str2 = str2.replace(str2[:n],x)
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():
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 = []
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.
print(L2)
Output:
f1 = myfile.read()
words = f1.split( )
myfile.seek(0)
lines = myfile.readlines()
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:
self.y = y
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):]
l1 = list()
for i in range(0,len(t1)):
if t1[i]%2==0:
l1.append(t1[i])
t2 = (11,13,15)
t3 = t1+t2
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):
return name
try:
name = validate_name(name)
print("Hello, {}!".format(name))
Output:
14. WAP to return the percentage of the marks obtained by a student using assert
statement.
def get_percentage(marks, total_marks):
try:
print("Percentage: {:.2f}%".format(percentage))
print("Error:", ae)
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
f = math.factorial(num)
Output:
if (n % i) == 0:
print(i,end=" ")
Output:
else:
smaller = num_1
hcf = i
Output:
if num_1>num_2:
greater = num_1
else:
greater = num_2
while(True):
lcm = greater
break
greater += 1
Output:
20. WAP to interchange the two numbers stored in two variables using another variable.
x = int(input("Enter the first number: "))
temp = x
x = y
y = temp
Output:
21. WAP to interchange the two numbers stored in two variables without using another
variable
x = int(input("Enter the first number: "))
x,y=y,x
Output: