PROGRAMS
PROGRAMS
OUTPUT :
#Comparison Operations
a=int(input("Enter first number : "))
b=int(input("Enter second number : "))
print("Comparison Operations :")
print(f"{a} == {b} : {a == b}")
print(f"{a} != {b} : {a != b}")
print(f"{a} > {b} : {a > b}")
print(f"{a} < {b} : {a < b}")
print(f"{a} >= {b} : {a >= b}")
print(f"{a} <= {b} : {a <= b}")
OUTPUT :
#Logical Operations
a=int(input("Enter first number : "))
b=int(input("Enter second number : "))
print("Logical Operations :")
print(f"{a} and {b} : {a and b}")
print(f"{a} or {b} : {a or b}")
print(f"not {a} : {not a}")
print(f"not {b} : {not b}")
OUTPUT :
#Bitwise Operations
a=int(input("Enter first number : "))
b=int(input("Enter second number : "))
print("Bitwise Operations :")
print(f"{a} & {b} : {a & b}")
print(f"{a} | {b} : {a | b}")
print(f"{a} ^ {b} : {a ^ b}")
print(f"~{a} : {~a}")
print(f"{a} << 2 : {a << 2}")
print(f"{a} >> 2 : {a >> 2}")
OUTPUT :
#Assignment Operations
a=int(input("Enter a number : "))
print("Assignment Operations :")
x=a
print(f"x = {a}")
x += 5
print(f"x += 5 : {x}")
x -= 3
print(f"x -= 3 : {x}")
x *= 2
print(f"x *= 2 : {x}")
x /= 2
print(f"x /= 2 : {x}")
x %= 3
print(f"x %= 3 : {x}")
x //= 2
print(f"x //= 2 : {x}")
x **= 2
print(f"x **= 2 : {x}")
OUTPUT :
#Identity Operations
a=int(input("Enter first number : "))
b=int(input("Enter second number : "))
print("Identity Operations :")
print(f"{a} is {b} : {a is b}")
print(f"{a} is not {b} : {a is not b}")
OUTPUT :
#Membership Operations
list1=[23,1,56,7,11,3]
e=int(input("Enter an element : "))
print("Membership Operations :")
print(f"{e} in {list1} : {e in list1}")
print(f"{e} not in {list1} : {e not in list1}")
OUTPUT :
Q2 Write a Python program to demonstrate type conversion.
print("Implicit Type Conversion : ")
a=10
b=1.5
c=a+b
print(f"Type of 'a' : {type(a)}")
print(f"Type of 'b' : {type(b)}")
print(f"Result of 'a + b' : {c}, Type of c : {type(c)}")
print("\nExplicit Type Conversion : ")
s="123"
print(f"Type of 's' : {type(s)}")
s1=int(s) #Converting string to integer
print(f"After conversion to integer : {s1}, Type: {type(s1)}")
s2=float(s1) #Converting integer to float
print(f"After conversion to float : {s2}, Type: {type(s2)}")
num = 29
print(f"Integer: {num}")
print(f"Binary: {bin(num)}")
print(f"Octal: {oct(num)}")
print(f"Hexadecimal: {hex(num)}")
OUTPUT :
Q3 Write a Python program to calculate the area of a triangle using
user input.
b=int(input("Enter the base of the triangle : "))
h=int(input("Enter the height of the triangle : "))
area=(b*h)/2
print("Area of triangle =",area)
OUTPUT :
OUTPUT :
OUTPUT :
OUTPUT 2 :
OUTPUT 4 :
Q5 WAP to check whether a number entered is a 3 digit number or
not.
y=int(input("Enter a number : "))
z=y//100
if(z>=1)and(z<=9):
print(y,"is a 3-digit number")
else:
print(y,"is not a 3-digit number")
OUTPUT 5 :
OUTPUT 7 :
OUTPUT 9 :
OUTPUT 10 :
OUTPUT 11 :
OUTPUT 1 :
OUTPUT 3 :
OUTPUT 4 :
Q5 WAP to print table of any number.
num=int(input("Enter a number : "))
print("Table of ",num)
for i in range(1,11):
print(num*i)
OUTPUT 5 :
OUTPUT 6 :
Q8 WAP to find the sum of first 50 Natural Numbers using for Loop.
sum=0
for i in range(1,51):
sum+=i
print("Sum of first 50 Natural Numbers =",sum)
OUTPUT 8 :
OUTPUT 10 :
OUTPUT 4 :
Q5 WAP to calculate the value of nCr
n = int(input("Enter the value of n : "))
r = int(input("Enter the value of r : "))
factn,factr,factnr=1,1,1
for i in range(1,n+1):
factn*=i
for j in range(1,r+1):
factr*=j
for k in range(1,n-r+1):
factnr*=k
nCr=factn//(factr*factnr)
print("The value of nCr is",nCr)
OUTPUT 5 :
OUTPUT 7 :
OUTPUT 8 :
for j in range(2,i):
if(i%j==0):
count += 1
if(count==0):
print(i,end=" ")
OUTPUT 10 :
OUTPUT 11 :
Q12 WAP to find the LCM (Least Common Multiple) of two numbers.
a=int(input("Enter first number : "))
b=int(input("Enter second number : "))
if(a>b):
large=a
else:
large=b
max=a*b
for i in range(large,max+1):
if(i%a==0)and(i%b==0):
lcm=i
break
print("The LCM of",a,"and",b,"is",lcm)
OUTPUT 12 :
if(n>1):
while(b<=n):
c = a+b
if(n==c):
print(n,"is a fibonacci number")
count=1
break
a=b
b=c
if(count==0):
print(n,"is not a fibonacci number")
OUTPUT 13 :
PATTERN PRINTING
Ques1 :
n=int(input("Enter number of rows : "))
for i in range(1,n+1):
for j in range(0,i):
print(i,end=" ")
print()
OUTPUT 1 :
Ques2 :
n=int(input("Enter number of rows : "))
for i in range(1,n+1):
for j in range(1,i+1):
print(j,end=" ")
print()
OUTPUT 2 :
Ques3 :
n=int(input("Enter number of rows : "))
for i in range(1,n+1):
for j in range(0,n+1-i):
print(i,end=" ")
print()
OUTPUT 3 :
Ques4 :
n=int(input("Enter number of rows : "))
for i in range(1,n+1):
for j in range(0,n+1-i):
print(5,end=" ")
print()
OUTPUT 4 :
Ques5 :
n=int(input("Enter number of rows : "))
for i in range(0,n):
for j in range(0,n+1-i):
print(j,end=" ")
print()
OUTPUT 5 :
Ques6 :
n=int(input("Enter number of rows : "))
a=1
for i in range(1,n+1):
for j in range(0,i):
print(a,end=" ")
a+=2
print()
OUTPUT 6 :
Ques7 :
n=int(input("Enter number of rows : "))
for i in range(1,n+1):
for j in range(i,n+1):
print(j,end=" ")
print()
OUTPUT 7 :
Ques8 :
n=int(input("Enter number of rows : "))
for i in range(1,n+1):
k=i
for j in range(i,0,-1):
print(k,end=" ")
k+=i
print()
OUTPUT 8 :
Ques9 :
n=int(input("Enter number of rows : "))
for i in range(n,0,-1):
for j in range(n,n-i,-1):
print(i,end=" ")
print()
OUTPUT 9 :
Ques10 :
n=int(input("Enter number of rows : "))
x=0
for i in range(1,n+1):
x+=i
y=x
for j in range(1,i+1):
print(y,end=" ")
y-=1
print()
OUTPUT 10 :
Ques11 :
n=int(input("Enter number of rows : "))
for i in range(1,n+1):
for j in range(n-i):
print(" ",end=" ")
for k in range(1,i+1):
print(k,end=" ")
print()
OUTPUT 11 :
Ques12 :
n=int(input("Enter number of rows : "))
for i in range(1,n+1):
for j in range(1,n+1):
if(i>=j):
print(i,end=" ")
else:
print(j,end=" ")
print()
OUTPUT 12 :
Ques13 :
n=int(input("Enter number of rows : "))
for i in range(n,0,-1):
for j in range(1,i+1):
if(j==i):
print(j,end=" ")
else:
print(j,"*",end=" ")
print()
OUTPUT 13 :
Ques14 :
s="Python"
for i in range(1,len(s)+1):
for j in range(i):
print(s[j],end="")
print()
OUTPUT 14 :
Ques15 :
n=int(input("Enter number of rows : "))
for i in range(1,n+1):
for j in range(n-i):
print(" ",end="")
for k in range(2*i-1):
print("*",end="")
print()
OUTPUT 15 :
Ques16 :
n = int(input("Enter a number : "))
a=n
b=n
for i in range(1,2*n):
for j in range(1,n+i+1):
if(j==a or j==b) :
print("*",end="")
else:
print(" ",end="")
print()
if(i<n):
a = a-1
b = b+1
else :
a = a+1
b = b-1
OUTPUT 16 :
Ques17 :
n = int(input("Enter a number : "))
a=n
for i in range(1,n+1):
for j in range(1,n+1):
if(j>=a) :
print("*",end=" ")
else:
print(" ",end="")
print()
a = a-1
OUTPUT 17 :
Ques18 :
n = int(input("Enter a number : "))
a=1
for i in range(1,n+1):
for j in range(1,n+1):
if(j>=a) :
print("*",end=" ")
else:
print(" ",end="")
print()
a = a+1
OUTPUT 18 :
Ques19 :
n = int(input("Enter a number : "))
a=1
b=n
for i in range(1,2*n+1):
if (i<=n):
for j in range(1,n+1):
if (j>=a):
print("*", end=" ")
else:
print(" ", end="")
print()
a += 1
else:
for j in range(1, n + 1):
if (j>=b):
print("*", end=" ")
else:
print(" ", end="")
print()
b -= 1
OUTPUT 19 :
OUTPUT 1 :
Q2 Given a list of fruits fruits = ["apple", "banana", "cherry"], print
each fruit using a for loop.
fruits=["apple","banana","cherry"]
print("The given list is:",fruits)
print("The list fruits has following elements:")
for i in fruits:
print(i)
OUTPUT 2 :
Q3 Given two tuples (1, 2, 3) and (4, 5, 6), concatenate them and
print the result.
t1=(1,2,3)
t2=(4,5,6)
print("Tuple t1:",t1)
print("Tuple t2:",t2)
t3=t1+t2
print("Concatenated Tuple:",t3)
OUTPUT 3 :
Q4 Write a program to replace all spaces in a string with hyphens
using replace().
s="Hi Rohan how are you?"
print("The given string is:",s)
print("New string is:",s.replace(" ","-"))
OUTPUT 4 :
OUTPUT 5 :
Q6 Write a Python program to find the key with the highest value in
the dictionary scores = {"Alice": 85, "Bob": 90, "Charlie": 88}.
scores={"Alice":85, "Bob":90, "Charlie":88}
print("The given dictionary is:",scores)
max=0
for i in scores:
if(max<scores[i]):
max=scores[i]
y=i
print("The key with highest value is:",y)
OUTPUT 6 :
for i in l1:
if(i not in l2):
l2.append(i)
print("List of unique elements:",l2)
OUTPUT 8 :
Q9 Write a Python program that takes a string, converts it into a list
of characters, reverses the list, and then joins it back into a string
to print the reversed string.
s=input("Enter a string: ")
l1=list(s)
print("List of characters:",l1)
rev=l1[::-1]
print("Reversed List:",rev)
s1=""
for i in rev:
s1+=i
print("Required String is:",s1)
OUTPUT 9 :
OUTPUT 1 :
OUTPUT 3 :
while(True):
print("Simple Calculator")
print("Select an operation:")
print("1. Add")
print("2. Subtract")
print("3. Multiply")
print("4. Divide")
print("5. Exit")
ch = input("Enter your choice (1/2/3/4/5): ")
if ch not in ['1', '2', '3', '4', '5']:
print("Invalid choice. Please select a valid operation.")
continue
if ch == '5':
print("Exit")
break
num1 = int(input("Enter the first number: "))
num2 = int(input("Enter the second number: "))
if ch == '1':
print(f"The result of addition is: {add(num1, num2)}")
elif ch == '2':
print(f"The result of subtraction is: {subtract(num1, num2)}")
elif ch == '3':
print(f"The result of multiplication is: {multiply(num1, num2)}")
elif ch == '4':
print(f"The result of division is: {divide(num1, num2)}")
OUTPUT 4 :
Q5 Write a function is_prime(n) that checks if a number is prime.
Use this function inside a program to check if a given number is
prime or not.
def is_prime(n):
count=0
for i in range(2,n):
if(n%i==0):
count+=1
if(count==0):
print(n,"is a Prime Number")
else :
print(n,"is not a Prime Number")
OUTPUT 5 :
OUTPUT 6 :
lst = [ ]
n = int(input("Enter number of elements : "))
for i in range(0, n):
ele = int(input("Enter element: "))
lst.append(ele)
print("The list is:", lst)
print("The largest element of the list is: " , find_largest(lst))
OUTPUT 7 :
Q8 Write a function celsius_to_fahrenheit(celsius) that converts
Celsius to Fahrenheit and another function
fahrenheit_to_celsius(fahrenheit) that converts Fahrenheit to
Celsius. Use these functions in a program to perform the
conversions.
def celsius_to_fahrenheit(x):
return (x*9//5)+32
def fahrenheit_to_celsius(y):
return (y-32)*5//9
OUTPUT 8 :
OUTPUT 10 :
Python File Operations
Q1. Write a Python program that reads and prints each line of a file
one by one using readline() in a loop.
with open('/content/drive/MyDrive/data.csv','r') as file:
line = file.readline()
while line:
print(line, end='')
line = file.readline()
OUTPUT 1 :
Q2. Write a program that appends "This is a new line." to an
existing file using the write() method.
file_obj = open('/content/drive/MyDrive/data.csv','a')
file_obj.write('\nThis is a new line.')
file_obj.close()
file_obj = open('/content/drive/MyDrive/data.csv','r')
print(file_obj.read())
file_obj.close()
OUTPUT 2 :
Q3. Write a Python program that reads the first 10 characters of a
file, then uses seek(5) to move the pointer to the 6th character, and
reads the next 5 characters from that position.
with open('/content/drive/MyDrive/data.csv', 'r') as file:
# Read the first 10 characters
first_10_chars = file.read(10)
print("First 10 characters:", first_10_chars)
OUTPUT 3 :
Q4. Write a Python program that reads a text file and counts the
number of words, lines, and characters in the file.
def count_file_stats(file_path):
num_words = 0
num_lines = 0
num_chars = 0
file_path = '/content/drive/MyDrive/data.csv'
words, lines, chars = count_file_stats(file_path)
OUTPUT 4 :
Q5. Write a Python program that takes user input and appends it to
a file. The program should continue accepting input until the user
enters "STOP".
file_path = '/content/drive/MyDrive/data.csv'
with open(file_path, 'a') as file:
while True:
user_input = input("Enter text to append (or 'STOP' to quit): ")
if user_input.upper() == "STOP":
break
file.write(user_input + "\n")
print("Input appended to file successfully!")
OUTPUT 5 :
writer.writeheader()
writer.writerows(student_data)
OUTPUT 6 :
Q7. Write a Python program that compares the contents of two files
line by line and reports any differences.
def compare_files(file1_path, file2_path):
with open(file1_path, 'r') as file1, open(file2_path, 'r') as file2:
line_num = 1
while True:
line1 = file1.readline()
line2 = file2.readline()
if line1 != line2:
print(f"Difference found at line {line_num}:")
print(f"File 1: {line1.strip()}")
print(f"File 2: {line2.strip()}")
line_num += 1
file1_path = '/content/drive/MyDrive/data.csv'
file2_path = '/content/drive/MyDrive/Matplotlib.csv'
compare_files(file1_path, file2_path)
print("File comparison complete.")
OUTPUT 7 :
Q8. Write a Python program that reads the contents of a file and
writes the lines in reverse order to a new file (i.e., last line first, first
line last).
def reverse_file_lines(input_file_path, output_file_path):
with open(input_file_path, 'r') as infile, open(output_file_path, 'w') as outfile:
lines = infile.readlines()
for line in reversed(lines):
outfile.write(line)
input_file_path = '/content/drive/MyDrive/Matplotlib.csv'
output_file_path = '/content/drive/MyDrive/output.txt'
reverse_file_lines(input_file_path, output_file_path)
print(f"File '{input_file_path}' reversed and written to '{output_file_path}'")
print('/n')
print("Original file is: ")
file_ob = open('/content/drive/MyDrive/Matplotlib.csv','r')
print(file_ob.read())
file_ob.close()
print('\n')
print("Reversed file is: ")
file_obj = open('/content/drive/MyDrive/output.txt','r')
print(file_obj.read())
file_obj.close()
OUTPUT 8 :
Q9. Write a program that reads a file and replaces all occurrences
of a given word with another word, saving the changes to the file.
def replace_word_in_file(file_path, old_word, new_word):
with open(file_path, 'r+') as file:
file_content = file.read()
new_content = file_content.replace(old_word, new_word)
file.seek(0)
file.write(new_content)
file.truncate()
file_path = '/content/drive/MyDrive/output.txt'
old_word = "is"
new_word = "IS"
OUTPUT 9 :
Q10. Write a Python program that reads a file and counts how many
times a specific word appears in the file.
file = open('/content/drive/MyDrive/output.txt','r')
word_count ={}
content = file.read()
words = content.split()
for word in words:
word = word.lower()
if word in word_count:
word_count[word] += 1
else:
word_count[word] = 1
file.close()
for word, count in word_count.items():
print(f"{word}: {count}")
OUTPUT 10 :
Python Packages
OUTPUT 1 :
Q2 Given the list of students' names ["Alice", "Bob", "Charlie",
"David"] and their corresponding scores [85, 92, 78, 90], plot a bar
chart to represent the scores of each student.
OUTPUT 2 :
import numpy as np
x = np.random.rand(100)
y = np.random.rand(100)
plt.scatter(x, y, color='green')
plt.title('Random Scatter Plot')
plt.xlabel('x')
plt.ylabel('y')
plt.show()
OUTPUT 3 :
import numpy as np
matrix1 = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
matrix2 = np.array([[9, 8, 7], [6, 5, 4], [3, 2, 1]])
result = np.dot(matrix1, matrix2)
print(result)
OUTPUT 4 :
OUTPUT 5 :
import numpy as np
data = np.array([10, 15, 7, 22, 17])
print("Mean:", np.mean(data))
print("Standard deviation:", np.std(data))
print("Median:", np.median(data))
print("Sum:", np.sum(data))
OUTPUT 7 :
OUTPUT 8 :
OUTPUT 9 :
import pandas as pd
import matplotlib.pyplot as plt
weather_data = pd.read_csv('weather.csv')
weather_data['Date'] = pd.to_datetime(weather_data['Date'])
weather_data['Month'] = weather_data['Date'].dt.month
monthly_avg_temp = weather_data.groupby('Month')['Temperature'].mean()
print(monthly_avg_temp)
plt.plot(weather_data['Date'], weather_data['Temperature'])
plt.title('Daily Temperature Over Time')
plt.xlabel('Date')
plt.ylabel('Temperature')
plt.xticks(rotation=45)
plt.show()
TKINTER
Q1 Write a Python program to create a basic Tkinter window with
the following properties:
● The window title should be "Welcome Window".
● The window should have a fixed size of 500x400 pixels.
● Add a label that says "Hello, Tkinter!" in the center of the window.
import tkinter as tk
def main():
window = tk.Tk()
window.title("Welcome Window")
window.geometry("500x400")
window.resizable(False, False)
label = tk.Label(window, text="Hello, Tkinter!", font=("Arial", 16))
label.pack(expand=True)
window.mainloop()
if __name__ == "__main__":
main()
OUTPUT 1 :
Q4 Create a login form with two input fields for username and
password. Add a "Login" button that validates the inputs:
● If the username is "admin" and the password is "password123",
display "Login successful" in a label below the button.
● If the credentials are incorrect, display "Invalid username or
password"
import tkinter as tk
def validate_login():
username = username_entry.get()
password = password_entry.get()
if username == "admin" and password == "password123":
result_label.config(text="Login successful", fg="green")
else:
result_label.config(text="Invalid username or password", fg="red")
def main():
window = tk.Tk()
window.title("Login Form")
window.geometry("400x300")
window.resizable(False, False)
tk.Label(window, text="Username:", font=("Arial", 14)).pack(pady=10)
global username_entry
username_entry = tk.Entry(window, font=("Arial", 14), width=25)
username_entry.pack(pady=5)
tk.Label(window, text="Password:", font=("Arial", 14)).pack(pady=10)
global password_entry
password_entry = tk.Entry(window, font=("Arial", 14), show="*", width=25)
password_entry.pack(pady=5)
tk.Button(window, text="Login", font=("Arial", 14),
command=validate_login).pack(pady=20)
global result_label
result_label = tk.Label(window, text="", font=("Arial", 14))
result_label.pack(pady=10)
window.mainloop()
if __name__ == "__main__":
main()
OUTPUT 4 :