0% found this document useful (0 votes)
53 views

PGT File of Cs

The document contains solutions to 14 Python programming questions. It includes sample inputs, outputs and code snippets for tasks like calculating compound interest, roots of a quadratic equation, pattern printing, string manipulation and more.

Uploaded by

lakshay150720
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)
53 views

PGT File of Cs

The document contains solutions to 14 Python programming questions. It includes sample inputs, outputs and code snippets for tasks like calculating compound interest, roots of a quadratic equation, pattern printing, string manipulation and more.

Uploaded by

lakshay150720
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
You are on page 1/ 22

HANSRAJ SMARAK SR

SEC SCHOOL

Session: 2023-2024
Computer science
“Practical File”

SUBMITTED TO:
Mrs. Seema Sharma
(PGT COMPUTER SCIENCE)
SUBMITTED BY:
Lakshay
Roll No: 20
Q1 WAP to accept your name and height (in inches), convert it into feet and
inches and display it in the following format: Hello I am, and my height is feet
and inches. Here nm, ft and inch are the variables holding name, height in feet
and inches.
INPUT
n=input("Enter your name:")
hi=float(input("Enter your height in inches:"))
hf=int(hi//2)
I=int(hi%12)
print("Hello I am" ,n ,"and my height is" ,hf, "feet and" ,I, "inches.")
OUTPUT

Q2 WAP to accept Principal, Time and Rate. The program should display the
Compound Interest calculated using the following formula: A=(1+R/100) T
CI=A-P
INPUT
principal=int(input("Enter the principal amount:"))
time=int(input("Enter the time period (in years):"))
rate=int(input("Enter the rate of interest (as a percentage):"))
rate=rate/100
interest=principal*(1+rate) ** time-principal
print("the compound interest is" ,interest)
OUTPUT
Q3 WAP to calculate the Radius of the sphere whose area (4πr2) is entered by
the user.
INPUT
Import math
surfacearea=int(input("Enter the surface area of the sphere:"))
radius=math.sqrt(surfacearea/(4*math.pi))
print("The radius of the sphere is:", radius)
OUTPUT

Q4 WAP to accept 3 coefficients of a quadratic equation and display its roots. Suppose the
equation is: ax2+bx+c, where a, b and c is entered by the user, then the root of the equation
is calculated as: Root1= (-b+√ (b 2 - 4ac))/2a Root2= (-b-√ (b 2 -4ac))/2a
INPUT

import math:
a=int(input("Enter the coefficient a:"))
b=int(input("Enter the coefficient b:"))
c=int(input("Enter the coefficient c:"))
discriminant=b**2-4*a*c
if discriminant > 0:
root1=(-b+math.sqrt(discriminant))/(2*a)
root2=(-b-math.sqrt(discriminant))/(2*a)
print(f"Root 1:{root1}")
print(f"Root 2:{root2}")

elif discriminant == 0:
root=-b/(2*a)
print(f"Root 1:{root}")
else:
real_part=-b/(2*a)
imaginary_part = math.sqrt(-discriminant)/(2*a)
root1=complex(real_part,imaginary_part)
root2=complex(real_part,-imaginary_part)
print(f"Root 1:{root1}")
print(f"Root 2:{root2}")
OUTPUT

Q5 WAP to take two inputs, day and month from the user. The program should
calculate which day of the year the given date is. Take days for all the month as
30 for simplicity. For e.g., if the user enters day=3 and month=2, then the
output must be Day of the year: 33
INPUT
day=int(input("Enter the day:"))
month=int(input("Enter the month:"))
dayofyear=(month-1)*30+ day
print(f"Day of the year:",dayofyear)
OUTPUT
Q6 WAP that accepts the number X and uses the appropriate Menu, performs
the following tasks:
a. Total number of digits in it.
b. Reversed number.
c. Whether it is palindrome or not.
d. Sum of all digits.
e. new number Y, which contains LSD at Hundreds place, total number of digits
at tens place and MSD at one's place.
INPUT
while True:
try:
X = int(input("Enter a number: "))
except ValueError:
print("Invalid input.Please enter a valid number.")
continue
print("\nMenu:")
print("1. Total number of digits")
print("2. Reversed number")
print("3. Check if it is palindrome")
print("4. Sum of all digits")
print("5. Transform the number")
print("6. Exit")
choice=input("Enter your choice (1/2/3/4/5/6): ")
if choice == '1':
print("Total number of digits:", len(str(X)))
elif choice == '2':
print("Reversed number:", int(str(X)[::-1]))
elif choice == '3':
if str(X) == str(X)[::-1]:
print("The number is a palindrome.is_palindrome(X)")
elif choice == '4':
print("Sum of all digits:", sum(int(digit) for digit in str(X)))
elif choice == '5':
lsd = X % 10
tens_place=len(str(X))
msd=int(str(X)[0])
Y=lsd * 100 + tens_place * 10 + msd
print("Transformed number:", Y)
elif choice == '6':
print("Exiting program.")
break
else:
print("Invalid choice. Please select a valid option.")
OUTPUT
Q7 WAP that accepts some numbers and displays the following data. The
process should continue when the user enters 0:
a. Sum of all the even numbers entered.
b. Total number of odd numbers entered.
c. Average of the numbers entered.
d. the largest and smallest number entered.
e. All the numbers that end with 4
INPUT
even_sum=0
odd_count=0
total_sum=0
largest=float('-inf')
smallest=float('inf')
numbers_ending_with_4=[]
number=[]
while True:
try:
num = float(input("Enter a number (enter 0 to finsh): "))
if num == 0:
break
if num % 2 == 0:
even_sum += num
if num % 2 != 0:
odd_count += 1
total_sum += num
largest = max(largest, num)
smallest = min(smallest, num)
if str(num).endswith('4'):
numbers_ending_with_4.append(num)
except ValueError:
print("Invalid input. Please enter a valid number.")
if total_sum != 0:
average = total_sum / (even_sum + odd_count)
else:
average=0
print(f"Sum of even numbers: {even_sum}")
print(f"Total number of odd numbers: {odd_count}")
print(f"Average of the numbers: {average}")
print(f"Largest number entered: {largest}")
print(f"Smallest number entered: {smallest}")
print(f"Numbers that end with 4: {numbers_ending_with_4}")
OUTPUT
Q8 WAP that accepts a number and displays its factorial in the following
format. Suppose the user enters 5, the output should be: 5! = 5 X 4 X 3 X 2 X 1
= 120
INPUT
n=int(input("Enter a number:"))
result=1
expression=f"{n}!="
for i in range(n,0,-1):
result*=i
expression +=f"{i}"
if i !=1:
expression +="*"
expression +=f"={result}"
print(expression)
OUTPUT

Q9 WAP that displays the following pattern:


A. INPUT
n=4
for i in range(1, n + 1):
print("*"* i)
A.OUTPUT

B. INPUT
n=4
current_number = 1
for i in range(1, n + 1):
for j in range(i):
print(current_number, end=' ')
current_number += 1
print()
B. OUTPUT
C. INPUT
start_char = ord('A')
current_char = start_char
n=4
for i in range(1, n + 1):
for j in range(i):
print(chr(current_char), end=' ')
current_char += 1
print()
C. OUTPUT

D. INPUT
rows= 4
current char='A'
for i in range(1, rows + 1):
for i in range(1, i + 1):
print(current_char, end=’ ‘)
current_char = chr(ord(current char) + 1)
Print()
D. OUTPUT
E. INPUT
n=4
for i in range(1, n + 1):
for j in range(1, i + 1):
print(chr(64 + j), end=' ')
print()
E. OUTPUT

F. INPUT
n=4
for i in range(1, n + 1):
for j in range(i):
print(i, end='')
print()
F. OUTPUT
Q10 WAP that accepts a string and capitalizes every alternate character. The
program should display the original and new strings.
INPUT
input_string = input("Enter a string:")
newstring = ""
for i in range(len(input_string)):
if i % 2 == 0:
newstring += input_string[i].upper()
else:
newstring += input_string[i]
print("Original String:", input_string)
print("New String:", newstring)
OUTPUT

Q.11 WAP that accepts email IDs of n users. Create two lists that stores user ID
and domain names separately.
INPUT
n=int(input("Enter the number of users:"))
user_ids=[]
domain_names=[]
for i in range(n):
email=input(f"Enter email ID for user{i+1}:")
user_id,domain=email.split('@')
user_ids.append(user_id)
domain_names.append(domain)
print("User IDs:",user_ids)
print("Domain Names:",domain_names)
OUTPUT

Q 12 WAP that accept a line and display each word on separate lines.
INPUT
line=input("Enter a line:")
words=line.split()
print("Words on separate lines:")
for word in words:
print(word)

OUTPUT

Q 13 WAP to accept an address containing pincode. Extract the pincode from


the address and display them. The process should continue till the user presses
'Y' or 'y'.
INPUT
while True:
address=input("Enter address with pincode(or 'Y' to exit):")
if address.lower() == 'y':
break
words = address.split()
for word in words:
if word.isdigit() and len(word) == 6:
print("Pincode:",word)
break
else:
print("No valid pincode found in the address.")
OUTPUT

Q 14 WAP that accepts a string. Extract all the digits from the string. If there
are digits, display: a. Sum of all the digits entered. b. Print:
i. Original string
ii. Digits
iii. Sum of digits If there are no digits.
iv. Print <original string> has no digits.
INPUT
input_string=input("Enter a string:")
digits=[int(char) for char in input_string if char.isdigit()]
if digits:
print("Original string:",input_string)
print("Digits:", digits)
print("Sum of digits:",sum(digits))
else:
print("{input_string} has no digits.")
OUTPUT

Q15 WAP that accepts WAP that accepts a list & determine whether the no
is present in 1st half or the 2nd half of the list.
INPUT
my_list=[int(x) for x in input("Enter a list of numbers separated by space:").split()]
number_to_find=int(input("Enter the number to find: "))
halfway_point=len(my_list) // 2
if number_to_find in my_list[:halfway_point]:

print(f"{number_to_find} is in the 1st half of the list.")


elif number_to_find in my_list[halfway_point:]:
print(f"{number_to_find} is in the 2nd half of the list.")
else:
print(f"{number_to_find} is not in the list.")

OUTPUT

Q16 WAP that accepts WAP that accepts a list & interchanges the 1st half
elements with the 2nd half elements of the list.
INPUT
my_list=[int(x) for x in input("Enter a list of numbers separated by space:").split()]
halfway_point=len(my_list)//2
interchanged_list=my_list[halfway_point:]+my_list[:halfway_point]
print("Original List:",my_list)
print("Interchanged List:",interchanged_list)

OUTPUT
Q17 WAP to create a list of strings. The list must create a new list same as
the first with its 1st character removed.
INPUT
original_list=['apple' ,'banana' ,'cherry' ,'date']
new_list=[word[1:] for word in original_list]
print("Original List:",original_list)
print("New List:",new_list)
OUTPUT

Q18 WAP to accept a list of numbers & perform left shift.


INPUT
my_list=[int(x) for x in input("Enter a list of numbers separated by space:
").split()]
shift_amount=int(input("Enter the number of positions to shift left: "))
shifted_list=my_list[shift_amount:]+my_list[:shift_amount]
print("Original List:",my_list)
print("Shifted List (Left):",shifted_list)
OUTPUT

Q19 WAP to accept a list of numbers & perform right shift.


INPUT
my_list=[int(x) for x in input("Enter a list of numbers separated by space: ").split()]
shift_amount=int(input("Enter the number of positions to shift right: "))
shifted_list=my_list[-shift_amount:] + my_list[:-shift_amount]
print("Original List:",my_list)
print("Shifted List (Right):",shifted_list)
OUTPUT

Q20 WAP to accept the nested tuple and print mean of each nested tuple.
The program must then display the mean of each mean calculated.
INPUT
nested_tuples=((1, 2, 3), (4, 5, 6), (7, 8, 9))
means=[sum(nested_tuple)/ len(nested_tuple) for nested_tuple in nested_tuples]
mean_of_means=sum(means)/ len(means)
print("Mean of each nested tuple:", means)

print("Mean of means:", mean_of_means)


OUTPUT

Q 21 WAP to accept roll number, name and marks of n students. Store the
data in the form of Dictionary in which keys are roll number and values are
in 33 the form of list of name and marks. The program must then ask the
roll number and display its corresponding marks.
INPUT
n=int(input("Enter the number of students: "))
student_data={}
for i in range(n):
roll_number=input(f"Enter Roll Number for student {i + 1}:")
name=input(f"Enter Name for student {i + 1}:")
marks=int(input(f"Enter Marks for student {i + 1}:"))
student_data[roll_number]=[name, marks]
roll_number_to_find=input("Enter Roll Number to display corresponding
marks:")
if roll_number_to_find in student_data:
print(f"The marks for Roll Number {roll_number_to_find}are:
{ student_data [roll_numbe _to_find][1]}")
else:
print(f"Roll Number {roll_number_to_find} not found.")
OUTPUT

Q 22 Given a dictionary: X={k1: v1, k2: v2, k3: v3} Create another dictionary
with opposite mapping. le. Y={ v1: k1, v2: k2, v3: k3}
INPUT
X={'k1':'v1','k2':'v2','k3':'v3'}
Y={value:key for key,value in X.items()}
print("Original dictionary X:",X)
print("New dictionary Y with opposite mapping:",Y)
OUTPUT
Q 23 WAP to accept the string and display total number of
occurrences of each character.
INPUT
input_string=input("Enter a string:")
char_count={}
for char in input_string:
if char in char_count:
char_count[char]+=1
else:
char_count[char]=1
for char, count in char_count.items():
print(f"Character'{char}' occurs {count} times.")
OUTPUT
Q 24 A dictionary D1 has values in the form of list of numbers write a program
to create a new dictionary D2 having same keys as D1 one but values are as
sum of list of values
INPUT
D1={'key1':[1, 2, 3],'key2':[4, 5, 6],'key3':[7, 8, 9]}
D2={}
for key,values in D1.items():
D2[key]=sum(values)
Print("D2:", D2)
OUTPUT

Q 25 WAP to perform to perform sorting on list of numbers.


INPUT
numbers = [5, 2, 8, 1, 3]
numbers.sort(reverse=True)
print("Sorted numbers in descending order:", numbers)
OUTPUT

You might also like