0% found this document useful (0 votes)
21 views67 pages

CPP Lab Manual

The document outlines various programming exercises, including algorithms, pseudocode, and flowcharts for checking if a number is odd or even, calculating the sum of the first N natural numbers, and generating an electricity bill based on unit consumption. It also includes Python programs for swapping values, circulating values of N variables, calculating distances between two points, and displaying various number and star patterns. Additionally, it features viva questions related to programming concepts and practices.
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)
21 views67 pages

CPP Lab Manual

The document outlines various programming exercises, including algorithms, pseudocode, and flowcharts for checking if a number is odd or even, calculating the sum of the first N natural numbers, and generating an electricity bill based on unit consumption. It also includes Python programs for swapping values, circulating values of N variables, calculating distances between two points, and displaying various number and star patterns. Additionally, it features viva questions related to programming concepts and practices.
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/ 67

Ex.

Ex. NoNo 1B
1A SUM OF FIRST
TO CHECK N NATURAL
WHETHER THENUMBERS
NUMBER IS
ODD OR EVEN
Date
Date
AIM:
To develop a problem analysis chart, algorithm, pseudocode and flow chart to check the number is odd
or even.

PROBLEM ANALYSIS CHART

Phase Details

Problem To check whether the number is odd even

Input An integer number N


Read N. If N % 2==0, then Print N is “Even” otherwise print N is
Process
“Odd”.
Output “Even” if divisible by 2, otherwise “Odd”
ALGORITHM:
Step 1: Start
Step 2 : Read the value of N.
Step 3 : If N%2==0, then display “Even” else display “Odd”.
Step 4 : Stop.

PSEUDOCODE :
BEGIN
INPUT number
IF number MOD 2 = 0 THEN
PRINT "The number is Even"
ELSE
PRINT "The number is Odd"
ENDIF
END

RESULT:
Thus, a problem analysis chart, algorithm, pseudocode, and flowchart are designed to check whether a
number is odd or even.

1
Ex. No 1C ELECTRICITY BILL

Date
AIM:
To draw a problem analysis chart, algorithm, pseudocode and flow chart to find the sum of first N
natural numbers.

PROBLEM ANALYSIS CHART

Phase Details

Problem Find the sum of first N natural numbers

Input A positive integer N

Process Calculate the sum using the formula Sum = N * (N + 1) / 2.

Output The sum of the first N natural numbers.


ALGORITHM:
Step 1: Start
Step 2: Input the value of n (the number up to which the sum is to be calculated).
Step 3: Calculate sum using the formula sum=n(n+1)/2
Step 4: Output the value of sum.
Step 5: Stop.

PSEUDOCODE :
BEGIN
INPUT n
SUM = (n * (n + 1)) / 2
OUTPUT SUM
END

RESULT:
Thus, a problem analysis chart, algorithm, pseudocode, and flowchart are designed to find the sum of the
first N natural numbers.

2
AIM:
To develop a problem analysis chart, algorithm, pseudocode and flow chart for generating Electricity
bill.

PROBLEM ANALYSIS CHART:

Phase Details
To calculate the total electricity bill based on the number of units
Problem
consumed using slab-wise tariff rates.

Input Units consumed (unit)


If unit ≤ 100 → amount = unit * 1.5
Else if unit ≤ 200 → amount = 150 + (unit - 100) * 2.5
Process Else if unit ≤ 300 → amount = 150 + 250 + (unit - 200) * 4
Else if unit ≤ 350 → amount = 150 + 250 + 400 + (unit - 300) * 5
Else → amount = 1500
Output Total amount of electricity bill (amount)

ALGORITHM:
Step1: Start
Step 2: Declare total unit consumed by the customer using the variable unit.
Step 3: If the unit consumed less or equal to 100 units, calculates the total amount of electricity
Consumed = units*1.5.
Step 4: If the unit consumed between 100 to 200 units, calculates the total amount of electricity
Consumed = (100*1.5) + (unit-100) *2.5)
Step 5: If unit consumed between 200 to 300 units, calculates total amount of electricity
consumed = ((100*1.5) + (200-100) * 2.5+(units-200) *4).
Step 6: If unit consumed between 300-350 units, calculates total amount of electricity
consumed = ((100*1.5) + (200-100) * 2.5+(300-200) *4+(units-350) * 5)
Step 7: If the unit consumed above 350 units, fixed charge - 1500/-
Step 8: End

PSEUDOCODE :

3
BEGIN
READ unit
IF unit <= 100 THEN
amount ← unit * 1.5
ELSE IF unit <= 200 THEN
amount ← 150 + (unit - 100) * 2.5
ELSE IF unit <= 300 THEN
amount ← 150 + 250 + (unit - 200) * 4
ELSE IF unit <= 350 THEN
amount ← 150 + 250 + 400 + (unit - 300) * 5
ELSE
amount ← 1500
ENDIF
PRINT "Electricity Bill = ", amount
END

RESULT:
The problem analysis chart, algorithm, pseudocode, and flowchart have been developed to generate an
electricity bill.

4
VIVA QUESTIONS
1. How does designing an algorithm help detect logical errors before coding? (TCS)
An algorithm breaks the problem into small, testable steps before coding. This helps find missing
conditions or wrong assumptions early.
2. What are the advantages of using a flowchart in a complex billing system? (Infosys)
Flowcharts show the flow of calculations, decisions, and loops clearly. They make complex logic
easier to understand, debug, and discuss.
3. Why is it important to handle boundary conditions in electricity billing flowcharts?
(Capgemini)
Correct slab selection at unit boundaries (like 100, 200 units) avoids billing errors, customer
complaints, and legal issues.
4. How can loops be represented in a flowchart for retail billing with multiple items? (Cognizant)
By drawing an arrow from a decision block (“more items?”) back to item entry, repeating until no
more items are left.
5. Explain how decision blocks help compute three-phase AC current differently for star and
delta. (Accenture)
The decision block checks connection type; based on yes/no, applies the correct formula for either
star or delta.
6. What is the difference between sequential and conditional flow? (Wipro)
Sequential flow follows steps one after another. Conditional flow adds decision points, so the path
can branch based on conditions.
7. How can modular flowcharts help in large systems? (IBM)
Breaking a large system into smaller flowcharts makes design clearer, easier to test, and reuses
common sub-processes.
8. Why do we use iteration in scientific problems like sine series? (HCL)
The series adds multiple terms; iteration naturally shows repeated addition until the required
accuracy or term count.
9. Give an example of parallel processes in a billing flowchart. (Tech Mahindra)
Calculating discount and tax separately, then adding both to the subtotal before the final bill.
10. What challenge might appear when turning flowcharts into code? (Mindtree)
Flowcharts may not show low-level details like variable types, error checks, or data validation,
which must be added in code.

5
Ex. No 2A SWAP THE VALUES OF TWO VARIABLES

Date

AIM:
To write a Python program for exchange the values of two variables.

ALGORITHM:

Step 1: Start
Step 2: Input two variables a and b
Step 3: Swap values using tuple unpacking: a, b = b, a
Step 4: Output swapped values of a and b
Step 5: End

PROGRAM:
# Swapping without a temporary variable
a=5
b = 10
print("Before swap:")
print("a =", a)
print("b =", b)
# Swap
a, b = b, a
print("After swap:")
print("a =", a)
print("b =", b)

OUTPUT:
Before swap:
a=5
b = 10
After swap:
a = 10
b=5

RESULT:
Thus the program for swapping the values of two variables have been written and executed
successfully.

6
Ex. No 2B CIRCULATE THE VALUES OF N VARIABLES

Date

AIM:
To write a python program for circulating the values of n variables using function.
ALGORITHM:
Step 1: Start
Step2: Define a List named list.
Step 3: Get the input n value to rotate the values.
Step 4: Perform the following Step b=a[n:]+a[:n], using slice operator
Step 5: Print the rotated values.
Step 6: Stop

PROGRAM:
list=[1,2,3,4,5]
print ("Original list",list)
n=int(input("Enter the shift location")) #Shift 2 location
rotate_list=list[n:]+list[:n]
print("Rotate list",rotate_list)

OUTPUT:
Original List = [1, 2, 3, 4, 5]
Enter the shift location 2
Rotate list= [3, 4, 5, 1,2]

RESULT:
Thus the program for circulating the values of n variables has been written and executed successfully.

7
Ex. No 2C DISTANCES BETWEEN TWO POINTS

Date

AIM:
To write a python program for calculating the distance between two points.
ALGORITHM:
Step 1: Start
Step 2: Take a two points as an input from a user.
Step 3: Calculate the difference between the corresponding X-coordinates
Step 4: X2 - X1 and Y-coordinates. Y2 - Y1 of two points.
Step 5: Print the values
Step 6: Stop

PROGRAM:
import math
a=input("Enter first coordinate : ")
p1 = a.split(",")
b=input("Enter second coordinate : “)
p2 = b.split(",")
distance = math.sqrt( ((int(p1[0])-int(p2[0]))**2)+((int(p1[1])-int(p2[1]))**2) )
print("Distance between ", a,"and", b, "is",distance)

OUTPUT:
Enter first coordinate: 4,0
Enter second coordinate: 6,6
Distance between 4,0 and 6, 6 is 6.324555320336759

RESULT:
Thus the program for circulating the values of n variables has been written and executed successfully.

8
VIVA QUESTIONS

1. Explain why multiple assignment (a,b = b,a) works in Python but not in some languages.
(Infosys)
Python packs values into a tuple and unpacks them in one step, while some languages require a
temporary variable.
2. What happens if user input isn’t converted before calculations? (TCS)
Input returns strings; adding them joins them as text, e.g., '2'+'3'→'23' instead of numeric 5.
3. Why is floating point precision important in distance calculations? (Capgemini)
Small floating-point errors can matter in scientific or engineering applications where precise
distance is critical.
4. How do you handle exchanging values of more than three variables? (Wipro)
Use slicing or unpacking: a,b,c = c,a,b or lst = lst[1:] + lst[:1] to rotate values efficiently.
5. Give an example where using expression instead of statement helps. (IBM)
max_val = x if x>y else y replaces multi-line if-else with a concise expression.
6. What does dynamic typing allow when swapping variables? (Cognizant)
The same code can swap ints, floats, or strings without specifying types, thanks to Python’s
flexibility.
7. Explain difference between input() and raw_input() in Python 2. (HCL)
raw_input() returned a string; input() evaluated as Python code. Python 3 kept only the safe version.
8. How to avoid division by zero when calculating distance? (Accenture)
Add a check: if denominator or divisor is zero, handle separately or skip calculation.
9. Why is operator precedence important in expressions like a+b*c? (Tech Mahindra)
Multiplication has higher precedence, so b*c runs before adding to a. Wrong grouping changes the
result.
10. What happens if you mix string and number in an expression? (Mindtree)
Python raises a TypeError, because it can’t directly add or multiply different types without
conversion.

9
Ex. No 3A NUMBER PATTERNS

Date

AIM:
To write a Python Program for displaying the number pattern.

ALGORITHM:
Step 1: Start
Step2: Define the depth value.
Step 3: Outer loop will print number of rows.
Step 4: Inner loop will print the value of i for each iteration.
Step 5: Print number.
Step 6: Line after each row to display pattern correctly.
Step 7: Stop.

PROGRAM:
depth = 6
for number in range(depth):
for i in range(number):
print(number, end=" ")
print()

OUTPUT:
1
22
333
4444
55555

RESULT:
Thus the program for displaying the number pattern has been written and executed successfully.

10
Ex. No 3B INCREMENTING NUMBER PATTERN
PROBLEMS
Date

AIM:
To write a Python program for displaying the incrementing number pattern.

ALGORITHM:
Step 1: Start
Step 2: Initialize x=0 and perform the operation
Step 3: Reassign it x=x+1 to increment a variable value by 1.
Step 4: Print x then the output will appear
Step 5: The value of x is incremented by 1
Step 6: Stop

PROGRAM:
depth = 6
for number in range(1, depth):
for i in range(1, number + 1):
print(i, end=' ')
print( )

OUTPUT:
1
12
123
1234
12345

RESULT:
Thus the program for displaying the incrementing number pattern has been written and executed
Successfully.

11
Ex. No 3C PYRAMID PATTERN PROBLEMS WITH STARS

Date

AIM:
To write a python program for displaying pyramid pattern with star.

ALGORITHM:
Step 1: Start
Step 2: rows = input("Enter the number of rows: ")
Step 3: # Outer loop will print the number of rows.
Step 4: for i in range(0, rows):
Step 5: # This inner loop will print the stars.
Step 6: for j in range(0, i + 1):
Step 7: print("*", end=' ')
Step 8: # Change line after each iteration.
Step 9: print(" ")
Step 10: Stop

PROGRAM:
def pyramid(n):
for m in range(0, n):
for i in range(0, m+1):
print("* ",end="")
print("\n")
n=5
pyramid(n)

OUTPUT:
*
**
***
****
*****

RESULT:
Thus the program for displaying pyramid pattern with star has been written and executed successfully.

12
13
Ex. No 3D INVENTED SEMI-PYRAMID PATTERN
PROBLEM WITH DESCENDING ORDER OF
Date NUMBERS

AIM:
To write a program for printing invented semi-pyramid pattern problem with descending order of
numbers.

ALGORITHM:
Step 1: Start
Step 2: Define the depth value
Step 3: Reversed loop for downward inverted pattern
Step 4: Increment in count after each iteration
Step 5: Print number
Step 6: Start

PROGRAM:
depth = 5
for i in range(depth,0,-1): n = i
for j in range(0, i):
print(n, end=' ')
print("\n")

OUTPUT:
55555
4444
333
22
1

RESULT:
Thus the program for printing invented semi-pyramid pattern problem with descending order of
numbers has been written and executed successfully.

14
Ex. No 3E STAR PATTERN

Date

AIM:
To write a python program for displaying star pattern.

ALGORITHM:
Step 1: Start
Step 2: Read the n value
Step 3: Find k is used to print the space
Step 4: Outer loop to print number of rows
Step 5: Inner loop is used to print number of space
Step 6: Decrement in k after each iteration
Step 7: This inner loop is used to print stars
Step 8: Downward triangle Pyramid
Step 9: Output for downward triangle pyramid
Step 10: Inner loop will print the spaces
Step 11: Increment in k after each iteration
Step 12: This inner loop will print number of stars
Step 13: Stop

PROGRAM:

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


for i in range(0, n):
for j in range(0, i + 1):
print("*", end=' ')
print()
for i in range(n, 0, -1):
for j in range(0, i - 1):
print("*", end=' ')
print()

15
OUTPUT:
*
**
***
****
*****
******
*****
****
***
**
*

RESULT:
Thus the program for displaying star pattern has been written and executed successfully.

16
Ex. No 3F RIGHT-ANGLED TRIANGLE PATTERN
WITH SAME CHARACTER
Date

AIM:
To write a python program for displaying right angles triangle pattern with same character.

ALGORITHM:
Step 1: Start
Step 2: First, we get the height of the pyramid rows from the user.
Step 3: In the first loop, we iterate from i = 0 to i = rows.
Step 4: In the second loop, we print numbers starting from 1 to j, where j ranges from 0 to i.
Step 5: After each iteration of the first loop, we print a new line.
Step 6: Stop

PROGRAM:
def letter_range(start, end):
for i in range(start, end):
for j in range(65, i + 1):
print(f"{chr(j)}", end="")
print("")
letter_range(65, 75)

OUTPUT:
A
AB
ABC
ABCD
ABCDE
ABCDEF
ABCDEFG
ABCDEFGH
ABCDEFGHI
ABCDEFGHIJ

RESULT:
Thus the program for displaying right angles triangle pattern with same character has been written and
executed successfully.
17
18
Ex. No 4A IMPLEMENTING REAL TIME /TECHNICAL
APPLICATION USING LISTS
Date

VIVA QUESTIONS

1. How do loops help generate number patterns? (TCS)


Loops repeat print statements with changing values, which builds structured patterns like pyramids,
triangles, or series.
2. What is the difference between for and while loops? (Infosys)
for loops run for a known number of iterations; while loops keep running until a condition becomes
false.
3. Why is indentation crucial in nested loops? (Capgemini)
Incorrect indentation can mix inner and outer loops, leading to wrong patterns or infinite loops.
4. How do you print a pyramid pattern of stars? (Cognizant)
Use nested loops: outer loop for each row, inner loop for spaces and stars, adjusting counts each
row.
5. Why use conditionals inside loops? (Accenture)
To change output based on row, column, or number (e.g., only printing even numbers or skipping
certain positions).
6. Explain how to print Fibonacci series up to n terms. (Wipro)
Start with two variables (0,1); use loop to add previous two, print, and shift values until n terms are
done.
7. What happens if loop termination condition is missing? (IBM)
The loop may run infinitely, using memory and CPU until forced to stop.
8. Why is range() useful in number series? (HCL)
It creates sequences efficiently, avoiding manual counters, and supports custom start, stop, and step
sizes.
9. How to print an inverted pyramid? (Tech Mahindra)
Reverse loop order: outer loop reduces row number; inner loops adjust spaces and stars accordingly.
10. When do we need nested conditionals inside loops? (Mindtree)
When the output depends on multiple conditions (e.g., number divisible by both 2 and 3 in a
pattern).

AIM:
To write a python program for implementing real time/technical application using list.
19
ALGORITHM:
Step 1: Start
Step 2: Perform list operations like concatenation(+), repetition(*), membership(in) and slicing.
Step 3: Insert new element in list by using append() method.
Step 4: Insert another collection like list by using extend() method.
Step 5: Remove an element from list by using remove ().
Step 6: Clear the list by using list.clear() method.
Step 7: Stop.

PROGRAM:
list1=["newspaper","articles","books"]
list2=["e-paper","journals"]
print(list1+list2)
print(list1*2)
print("book" in list1)
item=input("Enter the new item to add to list")
list1.append("Magazines")
print("List after appending is",list1)
item=input("Enter the item to be removed from list")
list1.remove(item)
print("List after removing is",list1)
list1.extend(list2)
print("List after extending is",list1)
list1.pop()
print("List after popping is",list1)
list2.clear() print(list2)

OUTPUT:
['newspaper', 'articles', 'books', 'e-paper', 'journals']
['newspaper', 'articles', 'books', 'newspaper', 'articles', 'books'] False Enter the new item to add to
listmagazines
List after appending is ['newspaper', 'articles', 'books', 'Magazines'] Enter the item to be removed from
Listarticles

List after removing is ['newspaper', 'books', 'Magazines']


List after extending is ['newspaper', 'books', 'Magazines', 'e-paper', 'journals']
List after popping is ['newspaper', 'books', 'Magazines', 'e-paper']

20
Ex. No 4B IMPLEMENTING REAL TIME /TECHNICAL
APPLICATION USING TUPLES
Date

RESULT:
Thus the above program to perform list operations was done and output was verified successfully.

AIM:
To write a python program for implementing real time/technical application using tuples.

21
ALGORITHM:
Step 1: Start
Step 2: Perform tuple operations like concatenation(+), repetition(*), membership(in) and slicing.
Step 3: Perform indexing in tuple by using index() method.
Step 4: Return number of elements in tuple by using count() method.
Step 6: Clear the tuple by using tuple.clear() method.
Step 7: Stop.

PROGRAM:
tuple1=("accelerator","brake","clutch") tuple2=("gear","mirror") print(tuple1+tuple2) print(tuple1*3)
print("brakes" in tuple1)
print("slicing in tuple",tuple1[1:]) item=input("Enter the element name")
print("total no of times",item,"is found in tuple2",tuple2.count(item)) print("Element",item," is found
in
tuple1 at",tuple2.index(item))

OUTPUT:
('accelerator', 'brake', 'clutch', 'gear', 'mirror')
('accelerator', 'brake', 'clutch', 'accelerator', 'brake', 'clutch', 'accelerator', 'brake', 'clutch')
False
slicing in tuple ('brake', 'clutch')
Enter the element namegear
total no of times gear is found in tuple2 1 Element gear is found in tuple1 at 0

RESULT:
Thus the above program to perform tuple operations was done and output was verified successfully.

22
VIVA QUESTIONS

1. Why are lists preferred when data needs to change? (TCS)


Lists are mutable, so we can add, remove, or update items anytime, unlike immutable tuples.
2. Give an example where a tuple is better than a list. (Infosys)
For fixed data like months of the year or car engine specifications, tuples prevent accidental
changes.
3. How to merge two lists? (Capgemini)
Use + operator (list1 + list2) or extend method (list1.extend(list2)).
4. How can we find how many items are in a list? (Cognizant)
Use len(list) to get the number of elements quickly.
5. Explain list slicing with an example. (Accenture)
list[1:4] gets elements from index 1 to 3; useful to get sublists without loops.
6. How do you check if an item exists in a list? (Wipro)
Use if item in list: which returns True or False.
7. What happens if you try to modify a tuple? (IBM)
Python raises a TypeError because tuples are immutable.
8. How can lists be used to model car components? (HCL)
Store components as items in a list, e.g., ['engine', 'wheels', 'seats'], and update when new parts are
added.
9. Difference between append() and insert(). (Tech Mahindra)
append() adds at end; insert(index, item) adds at specific position.
10. What is the benefit of using tuples in large data? (Mindtree)
They’re faster and use less memory because they don’t allow changes.

23
Ex. 5A IMPLEMENTING REAL TIME /TECHNICAL
No APPLICATION USING SET

Date

AIM:
To write a python program for implementing real time/technical application using set.

ALGORITHM:
Step 1: Start
Step 2: Perform set operations like concatenation(+), repetition(*), membership(in).
Step 3: Insert new element in set by using add() method.
Step 4: Insert another collection like set by using update() method.
Step 5: Remove an element from set by using remove ().
Step 6: Clear the set by using set.clear() method.
Step 7: Stop.

PROGRAM:
set1={"perl","Python","C"}
set2={"C#","BASIC","C"} tuple1=("FORTRAN","COBOL")
print(set1|set2) print(set1&set2) print(set1-set2) item=input("Enter the new data") set1.add(item)
print("set after adding new item",set1) set1.update(tuple1)
print("set after updation",set1) item=input("Enter item to be removed") set1.remove(item) print(set1)
set1.clear() print(set1)

OUTPUT:
{'C', 'C#', 'perl', 'BASIC', 'Python'}
{'C'}
{'perl', 'Python'}
Enter the new datajava
set after adding new item {'C', 'perl', 'java', 'Python'}
set after updation {'FORTRAN', 'Python', 'C', 'COBOL', 'perl', 'java'} Enter item to be removedperl
{'FORTRAN', 'Python', 'C', 'COBOL', 'java'}
set()

RESULT:
Thus the above program to perform set operations was done and output was verified successfully.

24
Ex.No 5B IMPLEMENTING REAL TIME
/TECHNICAL APPLICATION USING
Date DICTIONARIES

AIM:
To write a python program for implementing real time/technical application using dictionaries.

ALGORITHM:
Step 1: Start
Step 2: Perform dictionary operations like adding new element to dictionary.
Step 3: Update dictionary with another collection of data.
Step 4: Display the items in dictionary using items() method.
Step 5: Search an element in dictionary by using key value.
Step 6: Stop.

PROGRAM:
dict1={1:"gear",2:"brake",3:"clutch"}
dict2={5:"mirror"}
print(dict1.items())
flag=0
for key,value in dict1.items():
print(key,"->",value)
print("Adding new value")
key=input("Enter new key")
value=input("Enter new value")
dict1[key]=value print("Dictionary after adding new item",dict1.items())
print("Updating dictionary")
dict1.update(dict2)
print("Dictionary after updation",dict1.items())
key1=input("Enter key to search")
for key,value in dict1.items():
if(key==key1):
flag=1
print(key,"->",value)
if(flag==0):
print("Search item not found")
dict1.update({7:"glass"})
print(dict1.items())
print(dict1.keys())
25
dict1.pop(2)
print(dict1.items())
print(dict1.clear())

OUTPUT:
dict_items([(1, 'gear'), (2, 'brake'), (3, 'clutch')])
1 -> gear
2 -> brake
3 -> clutch Adding new value Enter new key6
Enter new value wheel
Dictionary after adding new item dict_items([(1, 'gear'), (2, 'brake'), (3, 'clutch'), ('6', 'wheel')])
Updating dictionary
Dictionary after updation dict_items([(1, 'gear'), (2, 'brake'), (3, 'clutch'), ('6', 'wheel'), (5, 'mirror')])
Enter key to search 7
Search item not found
dict_items([(1, 'gear'), (2, 'brake'), (3, 'clutch'), ('6', 'wheel'), (5, 'mirror'), (7, 'glass')])
dict_keys([1, 2, 3, '6', 5, 7])
dict_items([(1, 'gear'), (3, 'clutch'), ('6', 'wheel'), (5, 'mirror'), (7, 'glass')]) None

RESULT:
Thus the above program to perform dictionary operations was done and output was verified
successfully.

26
27
VIVA QUESTIONS
1. Why are sets useful for storing unique items? (TCS)
Sets automatically remove duplicates, ensuring each item appears only once.

2. Give an example where dictionary is better than list. (Infosys)


To store key-value pairs like car parts with prices: {'engine':50000, 'wheel':2000}.

3. Explain set union and intersection with example. (Capgemini)


Union combines all items; intersection keeps only common items, e.g., languages known by two
people.

4. How do you add an item to a set? (Cognizant)


Use set.add(item) to include a new element.

5. What happens if you add duplicate to a set? (Accenture)


It won’t be added; set keeps only one copy.

6. How to get all keys from a dictionary? (Wipro)


Use dict.keys() which returns a view of keys.

7. Explain difference between get() and direct access in dictionary. (IBM)


get() can return default if key is missing; direct access raises KeyError.

8. Why do sets not allow indexing? (HCL)


Sets are unordered collections; there’s no fixed position for items.

9. When is dictionary update() method used? (Tech Mahindra)


To merge another dictionary or add multiple new key-value pairs at once.

10. What data type is returned by dict.items()? (Mindtree)


It returns view objects containing (key, value) pairs, usable in loops.

28
Ex. No 6A FACTORIAL OF A NUMBER

Date

AIM:
To write a python program for finding factorial of number using function.

ALGORITHM:
Step 1: Start
Step 2: Read a number n
Step 3: Initialize variables: i = 1, fact = 1
Step 4: if i<= n go to Step 4 otherwise go to Step 7
Step 5: Calculate fact = fact * i
Step 6: Increment i by 1 (i=i+1) and go to Step 3
Step 7: Print fact
Step 8: Stop

PROGRAM:
def factorial(num):#function definition fact=1
for i in range (1, num+1):#for loop for finding factorial
fact=fact*i return fact
number=int(input("Please enter any number to find factorial: "))
result=factorial(number)
print("The factorial of %d = %d"%(number,result))

OUTPUT:
Please enter any number to find factorial: 6
The factorial of 6 = 720

RESULT:
Thus the program for finding factorial of number has been written and executed successfully.

29
Ex. No 6B AREAS OF SHAPES

Date
AIM:
To write a python program for finding areas of shapes.

ALGORITHM:
Step 1: Start.
Step 2: Get the input shape name from user.
Step 3: Call the function with specified shape name.
Step 4: Display the calculated result.
Step 5: Stop

PROGRAM:
def calculate_area(name):
name = name.lower()
if (name == "rectangle"):
l = int(input("Enter rectangle's length: "))
b = int(input("Enter rectangle's breadth: "))
rect_area = l*b
print(f"The area of rectangle is {rect_area}.")
elif(name == "square"):
s = int(input("Enter square's side length: "))
sqt_area = s * s
print(f"The area of square is {sqt_area}.")
elif(name == "triangle"):
h = int(input("Enter triangle's height length: "))
b = int(input("Enter triangle's breadth length: "))
tri_area =0.5 * b * h
print(f"The area of triangle is {tri_area}.")
elif(name == "circle"):
r = int(input("Enter circle's radius length: "))
pi = 3.14
circ_area = pi * r * r
print(f"The area of circle is {circ_area}.")
elif(name == 'parallelogram'):
b = int(input("Enter parallelogram's base length: "))
h = int(input("Enter parallelogram's height length: "))
para_area = b * h
print(f"The area of parallelogram is {para_area}.")
else:
print("Sorry! This shape is not available")
30
print("Calculate Shape Area")

shape_name=input("Enter the name of shape whose area you want to find: ")
calculate_area(shape_name)

OUTPUT:
Calculate Shape Area
Enter the name of shape whose area you want to find: square
Enter square's side length: 4
The area of square is 16.

RESULT:
Thus the program for finding area of shapes has been written and executed successfully.

31
Ex. No 6C LARGEST NUMBERS IN A LIST

Date

AIM:
To write a python program for finding the largest number in a list using function.

ALGORITHM:
Step 1: Get inputs from the user
Step 2: Assign first element into variable max
Step 3: initialize i=0.
Step 4: if (i<len(list)) then goto Step 5 else goto step 7
Step 5: if (list[i]>max) then max=list[i]
Step 6: increment i value by 1 and goto step 4
Step 7: Print the output
Step 8: End

PROGRAM:
def max_num_in_list( list ):
max = list[ 0 ]
for i in range(0,len(list)):
if list[i] > max:
max = list[i] return max print(max_num_in_list([8,105,63,7]))

OUTPUT:
105

RESULT:
Thus the program for finding the largest number in a list has been written and executed successfully.

32
VIVA QUESTIONS
1. Why use functions in Python? (TCS)
They help reuse code, make programs modular, and reduce repetition.

2. What is the difference between return and print? (Infosys)


return gives a value back to caller; print only shows it on screen.

3. How do you write a function with parameters? (Capgemini)


Use def name(param1, param2): to accept input inside the function.

4. What is recursion? (Cognizant)


A function calling itself; often used for factorial or Fibonacci series.

5. How to find largest number in list using function? (Accenture)


Loop through list, keep track of max value, return it at the end.

6. What happens if you don’t use return? (Wipro)


Function returns None by default; you can’t use its result in further calculations.

7. Why is defining functions useful in large projects? (IBM)


Makes code easier to read, test, and debug; each function handles a small task.

8. How can function compute area of circle? (HCL)


Use parameter radius, calculate 3.14*radius*radius, and return the area.

9. Difference between positional and keyword arguments? (Tech Mahindra)


Positional: based on order; keyword: specify name like area(radius=5).

10. What is a default parameter? (Mindtree)


A parameter with pre-set value; used if no argument is given by caller.

33
Ex. No 7A STRING REVERSE

Date

AIM:
To write a python program for displaying string reverse pattern.
ALGORITHM:
Step 1: Start
Step 2: Read the string from the user
Step 3: Calculate the length of the string
Step 4: Initialize rev = " " [empty string]
Step 5: Initialize i = length - 1
Step 6: Repeat until i>=0:
rev = rev + Character at position 'i' of the string i = i – 1
Step 7: Print rev
Step 8: Stop

PROGRAM:
def reverse_string(str):
str1 = "" for i in str:
str1 = i + str1 return str1
str = "python programming"
print("The original string is: ",str)
print("The reverse string is",reverse_string(str))

OUTPUT:
The original string is: python programming
The reverse string is gnimmargorpnohtyp

RESULT:
Thus the program for displaying string reverse pattern has been written and executed successfully.

34
Ex. No 7B PALINDROMES

Date

AIM:
To write a python program to check given string is palindrome or not.

ALGORITHM:
Step 1: Start
Step 2: Read the string from the user
Step 3: Calculate the length of the string
Step 4: Initialize rev = " " [empty string]
Step 5: Initialize i = length - 1
Step 6: Repeat until i>=0:
Step 6.1: rev = rev + Character at position 'i' of the string
Step 6.2:i = i – 1
Step 7: If string = rev
Step7.1: Print Yes"
Step 8: Else:
Step8.1: Print "No"
Step 9: Stop

PROGRAM:
def isPalindrome(str):
str1=""
for i in range(0,len(str)):
str1=str[i]+str1
if (str==str1):
return True
else:
return False
s = input("Enter the value")
ans = isPalindrome(s)
if (ans):
print("Yes")
else:
print("No")

OUTPUT:
Enter the value mom Yes

35
RESULT:
Thus the program to check whether given string is palindrome or not has been written and executed
successfully.

36
Ex. No 7C CHARACTER COUNTS

Date

AIM:
To create a python program to count the character in a string.

ALGORITHM:
Step 1: Define a string.
Step 2: Define and initialize a variable count to 0.
Step 3: Iterate through the string till the end and for each character except spaces, increment the count
Step 4: To avoid counting the spaces check the condition i.e. string[i] != ' '.

PROGRAM:
str1 = input("Please Enter your Own String : ") total = 0 for i in range(len(str1)):
total = total + 1
print("Total Number of Characters in this String = ", total)

OUTPUT:
Please Enter your Own String : python
Total Number of Characters in this String =6

RESULT:
Thus the program for counting the character in a string has been written and executed successfully.

37
Ex. No 7D REPLACING CHARACTERS

Date

AIM:
To write a python program to replace the string with another.

ALGORITHM:
Step 1: Start
Step 2: Get one input string from user.
Step 3: Get one character to replace in string from user.
Step 4: Using string replace() change the old character to new one.
Step 5: Print the modified string.
Step 6: Stop.

PROGRAM:
str1 = input("Please Enter your Own String : ")
ch = input("Please Enter your Own Character : ")
newch = input("Please Enter the New Character : ")
str2 = str1.replace(ch, newch)
print("\nOriginal String : ", str1)
print("Modified String : ", str2)

OUTPUT:
Please Enter your Own String: Hello world
Please Enter your Own Character: rl
Please Enter the New Character: r
Original String: Hello world
Modified String: Hello word

RESULT:
Thus the program for replacing the string with another string has been written and executed
successfully.

38
VIVA QUESTIONS

1. How to reverse a string in Python? (TCS)


Use slicing: string[::-1]. It creates a new string starting from end to start.

2. Explain what a palindrome is with an example. (Infosys)


A word or number that reads the same backward and forward, like 'madam' or '121'.

3. Why are strings immutable in Python? (Capgemini)


It ensures safety and efficiency; when changed, a new string is created instead of modifying the old
one.

4. How do you count number of times a character appears? (Cognizant)


Use string.count('a') which returns how often 'a' appears.

5. Explain replace() function in strings. (Accenture)


string.replace('old','new') returns a new string where all 'old' substrings are changed to 'new'.

6. Difference between upper() and capitalize(). (Wipro)


upper() makes all letters uppercase; capitalize() makes only first letter uppercase.

7. How to check if string starts with certain letter? (IBM)


Use string.startswith('A') which returns True or False.

8. What happens if you slice beyond string length? (HCL)


Python doesn’t raise error; it returns string up to available length.

9. How to remove spaces from both ends of a string? (Tech Mahindra)


Use strip(), which removes leading and trailing whitespace

10. Why use in operator with strings? (Mindtree)


To check if a substring exists: e.g., 'cat' in 'education' returns True.

39
Ex. No 8A PANDAS
Date

AIM:
To write a Pandas program to add, subtract, multiple and divide two Pandas Series.

ALGORITHM:
Step 1: Start.
Step 2: Create two pandas series.
Step 3: Perform numeric calculation like adding series, subtracting series, multiplication of series and
dividing series.
Step 4: Print the result.
Step 5: Stop.

PROGRAM:
import pandas as pd
ds1 = pd.Series([2, 4, 6, 8, 10])
ds2 = pd.Series([1, 3, 5, 7, 9]) ds = ds1 + ds2 print("Add two Series:") print(ds) print("Subtract two
Series:") ds = ds1 - ds2 print(ds)
print("Multiply two Series:") ds = ds1 * ds2 print(ds)
print("Divide Series1 by Series2:") ds = ds1 / ds2 print(ds)

OUTPUT:
Add two Series:

0 3
1 7

2 1

3 1

4 1

dtype: int64Subtract two Series:

0 1

40
1 1

2 1

3 1

4 1
dtype: int64Multiply two Series:

0 2
1 1
0 2.0
2 3 0
0
0
3 0 56
4 0
1 1.3 dtype: int64
3 Divide Series1 by Series2:
3
3
3
3
2 1.2
0
0
0
0 dtype: float64>
0
3 1.1
4
2
8
5
7
4

1.1
1
1
1
1
41
1
RESULT:
Thus the program for creating pandas has been written and executed successfully.

42
Ex. No 8B SCIPY

Date

AIM:
To write a program implementing Scipy Package.

ALGORITHM:
Step 1: Start.
Step 2: Import numpy package.
Step 3: Import io module from Scipy package.
Step 4: Create an array using ones().
Step 5: Create a dictionary.
Step 6: Save the contents to matrix file.
Step 7: Load the file.
Step 8: Print the data.
Step 9: Stop.

PROGRAM:
import numpy as np
from scipy import io as sio arr= np.ones((4, 4))
var={'ar': arr} sio.savemat('example.mat',var )
data = sio.loadmat('example.mat', struct_as_record=True)
print( data)

OUTPUT:
Array ([[ 1., 1., 1., 1.],
[ 1., 1., 1., 1.],
[ 1., 1., 1., 1.],
[ 1., 1., 1., 1.]])

RESULT:
Thus the program for creating Scipy has been written and executed successfully.

43
Ex. No 8C MATPLOTLIB

Date

AIM:
To write a Python programming to create a pie chart for the popularity of programming Languages.

ALGORITHM:
Step 1: Start.
Step 2: Import matplot library.
Step 3: Give the input as languages and its popularity.
Step 4: Create piechart by calling function pie() with various parameters.
Step 5: Print the chart.
Step 6: Stop.

PROGRAM:
import matplotlib.pyplot as plt
languages = 'Java', 'Python', 'PHP', 'JavaScript', 'C#', 'C++'
popuratity = [22.2, 17.6, 8.8, 8, 7.7, 6.7]
colors = ["#1f77b4", "#ff7f0e", "#2ca02c", "#d62728", "#9467bd", "#8c564b"]
explode = (0.1, 0, 0, 0,0,0)
plt.pie(popuratity, explode=explode, labels=languages, colors=colors, autopct='%1.1f%%',
shadow=True, startangle=140)
plt.axis('equal') plt.show()

OUTPUT:

44
RESULT:
Thus the program for printing plot has been written and executed successfully.

45
Ex. No 8D NUMPY

Date

AIM:
To write a python program with numpy package.

ALGORITHM:
Step 1: Start.
Step 2: Create a numpy array.
Step 3: Use various attributes for numpy array.
Step 4: Print the results.
Step 5: Stop.

PROGRAM:
import numpy as np
# Creating array object
arr = np.array( [[ 1, 2, 3], [ 4, 2, 5]] )
print(arr)
print("Array is of type: ", type(arr))
print("No. of dimensions: ", arr.ndim)
print("Shape of array: ", arr.shape)
print("Size of array: ", arr.size)
print("Array stores elements of type: ", arr.dtype)

OUTPUT:
[1 2 3]
[4 2 5]]
Array is of type: <class 'numpy.ndarray'> No. of dimensions: 2 Shape of array: (2, 3) Size of array: 6
Array stores elements of type: int64

RESULT:
Thus the program for to creating Numpy has been written and executed successfully.

46
VIVA QUESTIONS
1. What is a module? (TCS)
A separate Python file containing variables, functions, or classes for reuse in other programs.

2. Why use pandas? (Infosys)


It makes handling structured data easy using DataFrames and Series, with powerful tools for
analysis.

3. What is numpy used for? (Capgemini)


For fast mathematical and scientific calculations, especially large multi-dimensional arrays.

4. How to import only specific function from module? (Cognizant)


Use from module import function to avoid loading everything.

5. Explain what matplotlib helps with. (Accenture)


It’s used to draw plots, graphs, and charts for visualizing data.

6. How to install external libraries? (Wipro)


Use pip: e.g., pip install pandas downloads and installs the library.

7. Difference between module and package. (IBM)


Module: single file; package: folder containing modules with __init__.py.

8. What is scipy? (HCL)


Library built on numpy for advanced scientific functions like integration, optimization.

9. Why import numpy as np? (Tech Mahindra)


Shortens typing, so we can write np.array() instead of numpy.array().

10. Give an example of a standard library in Python. (Mindtree)


math for mathematical functions like sqrt(), sin(), etc.

47
Ex. No 9A FILE COPY

Date

AIM:
To write a python program to Copy the contents of the source file to destination file using copyfile
module.

ALGORITHM:
Step 1: Start
Step 2: Import the Copyfile module from shutil.
Step 3: Enter the source and destination file names.
Step 4: Copy the contents of the source file to destination file using copyfile module.
Step 5: End.

PROGRAM:
from shutil import copyfile
sourcefile = input("Enter source file name: ")
destinationfile = input("Enter destination file name: ")
copyfile(sourcefile, destinationfile)
print("File copied successfully!")
print("Contents of destination file :")
FileRead = open(destinationfile, "r")
print(FileRead.read()) FileRead.close()

OUTPUT:
Contents of the file "A.txt":
Hello world!
Execution:
Enter source file name: A.txt Enter destination file name: B.txt File copied successfully! Contents of
destination file:
Hello world!
Contents of the file "B.txt" after execution:
Hello world!

RESULT:
Thus the program for copying the contents of the source file to destination file using copyfile module
has been written and executed successfully.

48
Ex. No 9B WORD COUNT

Date

AIM:
To write a python program to count the string in a file.

ALGORITHM:
Step 1: Start.
Step 2: Import the Counter module from collections.
Step 3: Read the file.
Step 4: Split the word using split() function.
Step 5: Count the words using Counter.
Step 6: End.

PROGRAM:
from collections import Counter
FileName = input("Enter the file name : ")
CntFile = open(FileName, 'r')
print("Number of words in the file :")
print(Counter(CntFile.read().split()))
CntFile.close()

OUTPUT:
Contents of the file "test.txt":
hi hello and welcome
Execution:
Enter the file name : test.txt Number of words in the file :
Counter({'hi': 1, 'hello': 1, 'and': 1, 'welcome': 1})

RESULT:
Thus the program for counting the string in a file has been written and executed successfully.

49
Ex. No 9C LONGEST WORD IN FILE

Date

AIM:
To write a python program to create longest word in file.

ALGORITHM:
Step 1: Start.
Step 2: Read the file from which the longest word is to be found.
Step 3: Compare all the words in the file and find the maximum length.
Step 4: Print the longest word.
Step 5: End.

PROGRAM:
def longest_word(filename):
with open(filename, 'r') as infile:
words = infile.read().split()
max_len = len(max(words, key=len))
return [word for word in words if len(word) == max_len]
file_name=input("Enter the file name:")
print(longest_word(file_name))

OUTPUT:
Contents of the file "test.txt": hi hello and welcome Execution:
Enter the file name:test.txt ['welcome']

RESULT:
Thus the program for creating longest word in file has been written and executed successfully.

50
VIVA QUESTIONS

1. How do you open a file for reading? (TCS)


Use open('filename.txt', 'r'). 'r' stands for read mode.
2. Why use with open() statement? (Infosys)
It automatically closes file after block, preventing memory leaks.
3. How to copy contents to another file? (Capgemini)
Read source content with read(), open destination in write mode, then write content.
4. Explain purpose of readlines(). (Cognizant)
Returns list where each line in file is an item; useful for line-by-line processing.
5. How to count words in a file? (Accenture)
Read content, split by spaces, then use len() on resulting list.
6. What happens if you open non-existing file in read mode? (Wipro)
Python raises FileNotFoundError.
7. How to find longest word in file? (IBM)
Split content into words, then use max(words, key=len).
8. Difference between 'a' and 'w' modes? (HCL)
'a' appends to file; 'w' overwrites existing content.
9. What is file cursor? (Tech Mahindra)
Pointer showing current position for read/write; can move with seek().
10. What type of data does file.read() return? (Mindtree)
Returns the whole file content as a single string.

51
Ex. No 10 A IMPLEMENTING REAL TIME /TECHNICAL
APPLICATION USING EXCEPTION
Date HANDLING DIVIDE BY ZERO

AIM:
To write a program for implementing real time /technical application using exception handling divide
by zero.

ALGORITHM:
Step 1: We will take inputs from the user, two numbers.
Step 2: If the entered data is not integer, throw an exception.
Step 3: If the remainder is 0, throw divide by zero exception.
Step 4: If no exception is there, return the result.

PROGRAM:
try:
num1 = int(input("Enter First Number: "))
num2 = int(input("Enter Second Number: "))
result = num1 / num2
print(result)
except ValueError as e:
print("Invalid Input Please Input Integer...")
except ZeroDivisionError as e: print(e)

OUTPUT 1:
Enter First Number: abc
Invalid input please input integer...
OUTPUT 2:
Enter First Number: 43
Enter First Number: 0
Division by zero
OUTPUT 3:
Enter First Number: 331 2
Enter First Number: 4 83.0

52
RESULT:
Thus the program for implementing real time / technical application using exception handling divide
by
zero has been written and executed successfully.
53
54
Ex. No 10 B IMPLEMENTING REAL TIME /TECHNICAL
APPLICATION USINGEXCEPTION HANDLING
Date VOTER’S AGE VALIDITY

AIM:
To write a python program to for implementing real time /technical application using exception
handling voter’s age validity.

ALGORITHM:
Step 1: Start
Step 2: Accept the age of the person.
Step 3: If age is greater than or equal to 18, then display 'You are eligible to vote'.
Step 4: If age is less than 18, then display 'You are not eligible to vote'.
Step 5: Stop.

PROGRAM:
def main():
try:
age=int(input("Enter your age")) if age>18:
print("Eligible to vote") else:
print("Not eligible to vote")
#display exception's default error message except ValueError as err:
print(err) except:
print("An Error occured") print("rest of the code...") main()

OUTPUT 1:
Enter your age 30 Eligible to vote
OUTPUT 2:
Enter your age thirty
Invalid literal for int() with base 10: ' thirty' Rest of the code.

RESULT:
Thus the program for implementing real time / technical application using exception handling voter’s
age validity has been written and executed successfully.

55
VIVA QUESTIONS
1. What is exception? (TCS)
An error detected during execution, like ZeroDivisionError or ValueError.
2. Why handle exceptions? (Infosys)
To keep program running, show user-friendly message instead of crashing.
3. How to catch divide by zero error? (Capgemini)
Wrap code in try:, handle in except ZeroDivisionError:.
4. What is finally block? (Cognizant)
Code that runs always, whether exception happened or not.
5. Give example of real-time validation using exception. (Accenture)
Check voter's age: raise exception if age < 18, else continue.
6. What happens without exception handling? (Wipro)
Program stops immediately when error occurs, showing traceback.
7. What is custom exception? (IBM)
User-defined exception class for specific, meaningful errors.
8. Explain multiple except blocks. (HCL)
Handle different error types separately, e.g., ZeroDivisionError, ValueError.
9. How to raise an exception manually? (Tech Mahindra)
Use raise Exception("Message") to trigger an error.
10. Difference between error and exception? (Mindtree)
Error usually means serious issue; exception can often be handled in code.

56
Ex. No 11 PYGAME

Date

AIM:
To write a python program for simulate elliptical orbits using pygame.

ALGORITHM:
Step 1: Import the required packages
Step 2: Set up the colours for the elliptical orbits
Step 3: Define the parameters to simulate elliptical orbits
Step 4: Display the created orbits.

PROGRAM:
import pygame import math import sys pygame.init()
screen = pygame.display.set_mode((600, 300))
pygame.display.set_caption("Elliptical orbit")
clock = pygame.time.Clock()
while(True):
for event in pygame.event.get():
if (event.type == pygame.QUIT):
sys.exit()
xRadius = 250
yRadius = 100
for degree in range((0,360,10)):
x1 = int(math.cos(degree * 2 * math.pi / 360) * xRadius) + 300y1 = int(math.sin(degree * 2 *
math.pi / 360) * yRadius) + 150 screen.fill(0, 0, 0)
pygame.draw.circle(screen, (255, 0, 0), [300, 150], 35)
pygame.draw.ellipse(screen, (255, 255, 255), [50, 50, 500, 200], 1)
pygame.draw.circle(screen, (0, 0, 255), [x1, y1], 15)
pygame.display.flip()
clock.tick(5)

57
OUTPUT:

RESULT:
Thus the program for simulate elliptical orbits using pygame has been written and executed
successfully.

58
VIVA QUESTIONS

1. What is Pygame? (TCS)


A Python library to create games and multimedia applications.
2. Why initialize Pygame? (Infosys)
Use pygame.init() to set up modules like display and sound.
3. What does set_mode() do? (Capgemini)
Creates window with specified width and height for game screen.
4. Why use clock.tick()? (Cognizant)
Limits frame rate; keeps game speed consistent on all computers.
5. How to handle user input in Pygame? (Accenture)
Check events from pygame.event.get() for key presses, mouse clicks.
6. Explain role of RGB in Pygame colors. (Wipro)
Colors use red, green, blue values (0–255), e.g., (255,0,0) is red.
7. What is game loop? (IBM)
Repeats drawing screen, updating objects, handling events until quit.
8. Why load image before drawing? (HCL)
Loading prepares image object so it can be drawn each frame.
9. How to quit game safely? (Tech Mahindra)
Call pygame.quit() to free resources and close window.
10. Name two common Pygame modules. (Mindtree)
pygame.display for screen; pygame.mixer for sound.

59
Ex. No 12 SIMULATING BOUNCING BALL

Date

AIM:
To write a python program for simulate bouncing ball using pygame.

ALGORITHM:
Step 1: Import the necessary files for the implementation of thisPygame.
Step 2: Set the display mode for the screen using window Surface= pygame.
display.set_mode((500,400),0,32)
Step 3: Now set the display mode for the pygame to bouncepygame. display.set_caption("Bounce")
Step 4: Develop the balls with necessary colors.BLACK=(0,0,0)WHITE=(255,255,255)RED=(255,0,0)
GREEN=(0,255,0) BLUE=(0,0,255)
Step 5: Set the display information info=pygame.display.Info()
Step 6: Set the initial direction as down.
Step 7: Change the direction from down to up.
Step 8: Then again change the direction from upto down.
Step 9: Set the condition for quit.
Step 10: Exit from the pygame.

PROGRAM:
import os os.environ['PYGAME_HIDE_SUPPORT_PROMPT'] = "hide"import sys, pygame
from pygame.locals import * pygame.init()
speed = [1, 1]
color = (255, 250, 250)
width = 550
height = 300
screen = pygame.display.set_mode((width, height))
pygame.display.set_caption("Pygame bouncing ball") ball = pygame.image.load("ball.png")
rect_boundry = ball.get_rect()
while 1:
for event in pygame.event.get():
rect_boundry = rect_boundry.move(speed)
if rect_boundry.left < 0 or rect_boundry.right > width:
speed[0] = -speed[0]
if rect_boundry.top < 0 or rect_boundry.bottom > height:
speed[1] = -speed[1]
60
screen.fill(color)
screen.blit(ball, rect_boundry)
pygame.display.flip()
if event.type == QUIT:
pygame.quit()
sys.exit()

OUTPUT:

RESULT:
Thus the program for bouncing ball using Pygame has been written and executed successfully.

61
VIVA QUESTIONS

1. How to animate ball in bouncing game? (TCS)


Change x, y coordinates each frame; reverse direction on hitting wall.
2. Why check collision with window boundary? (Infosys)
To make ball bounce; keeps it inside screen area.
3. Explain role of speed variable. (Capgemini)
Controls how fast object moves; change sign to change direction.
4. How to detect key press for car movement? (Cognizant)
Check pygame.key.get_pressed() inside game loop.
5. What happens without clock.tick()? (Accenture)
Game runs too fast; speed depends on computer performance.
6. Why divide game into functions? (Wipro)
Improves clarity, reuse; keeps code organized (e.g., draw, update, handle events).
7. How to keep score in a game? (IBM)
Use variable to track points; increase when player achieves something.
8. Explain purpose of display.flip() or update(). (HCL)
Refreshes screen so changes appear to player.
9. Difference between static image and animated sprite. (Tech Mahindra)
Static image doesn’t move; sprite can change position or frame.
10. Why use rectangle objects for collision? (Mindtree)
Rect makes detecting overlap easy using built-in functions.

62
Ex. No 13 PERFECT NUMBER OR NOT

Date

AIM:
To Write a Python program to find whether a number is perfect number or not.
S
ALGORITHM:
Step 1: Start
Step 2: Get one input number n.
Step 3: Call the function perfect number using n as input.
Step 4: Find the divisors of n by using modulus operator.
Step 5: Find the sum of n divisors.
Step 6: if sum==n, print n is perfect number.
Step 7: Else n is not perfect number.
Step 8: Stop.

PROGRAM:
def perfect_number(n): sum = 0
for x in range(1, n): if n % x == 0:
sum += x return sum == n
n=int(input("Enter a number"))
res=perfect_number(n)
if(res==True):
print(n,"is perfect number")
else:
print(n,"is not perfect number")

OUTPUT 1:
Enter a number 6
6 is perfect number
OUTPUT 2:
Enter a number21
21 is not perfect number
RESULT:
Thus the program to find perfect number or not is written successfully and output is verified
63
64
VIVA QUESTIONS

1. What is a perfect number? (TCS)


A perfect number equals the sum of its proper divisors. Example: 28 = 1 + 2 + 4 + 7 + 14.

2. How do you find proper divisors of a number? (Infosys)


Loop from 1 to number–1 and check if the number is divisible (using modulus operator %).

3. Why do we exclude the number itself from its divisors? (Capgemini)


Including it would always make the sum greater than the number, which violates the perfect number
definition.

4. Is 1 a perfect number? Why or why not? (Cognizant)


No. 1 has no proper divisors except itself, so the sum is 0 which is not equal to 1.

5. What are some known perfect numbers? (Accenture)


6, 28, 496, and 8128 are common perfect numbers. All are even.

6. Can odd perfect numbers exist? (Wipro)


No odd perfect number has been found yet; it’s still an unsolved problem in number theory.

7. How does time complexity affect checking large numbers? (IBM)


Checking all divisors up to n–1 is inefficient; we can optimize by going only up to √n.

8. What data type is best to store large perfect numbers? (HCL)


Use long or bigint depending on language, as perfect numbers grow rapidly.

9. Can this logic be applied to check for abundant and deficient numbers? (Tech Mahindra)
Yes. Sum > number → abundant, sum < number → deficient, sum = number → perfect.

10. Is there a formula to generate perfect numbers? (Mindtree)


Yes. Euclid’s formula: If 2ⁿ−1 is prime (a Mersenne prime), then 2ⁿ⁻¹(2ⁿ−1) is perfect.

65
Ex. No 14 RIGHT ANGLE TRIANGLE OR NOT

Date

AIM:
To Write a Python program to find whether a triangle is right angled triangle or not.

ALGORITHM:
Step 1: Start
Step 2: Read the values for three sides of triangle.
Step 3: Square the sides of triangle.
Step 4: If (side3)2=(side2)2+(side1)2, print the triangle is right angled.
Step 5: Print the triangle is not right angled.
Step 6: Stop.

PROGRAM:
side1=int(input("Enter the first side:"))
side2=int(input("Enter the second side:"))
side3=int(input("Enter the third side:"))
a=(side2**2)+(side3**2)
b=(side1**2)+(side3**2)
c=(side1**2)+(side2**2)
if (a==side1**2 or b==side2**2 or c==side3**2):
print("This triangle is a right triangle.")
else:
print("This triangle is not a right triangle.")

OUTPUT:
Enter the first side:3
Enter the second side:5
Enter the third side:4

RESULT:
Thus the above program to find right angle triangle or not is written successfully and output was
verified successfully.

66
VIVA QUESTIONS
1. What condition defines a right-angled triangle? (TCS)
If square of the largest side equals the sum of squares of other two sides.
2. Why must we sort the sides before checking? (Infosys)
To make sure we treat the largest side as hypotenuse while applying the Pythagoras rule.
3. Can three sides of any length form a triangle? (Capgemini)
No. They must satisfy the triangle inequality: sum of any two sides > third side.
4. What is Pythagorean triplet? (Cognizant)
A set of three positive integers like 3, 4, 5 that satisfy a² + b² = c².
5. Can a triangle have more than one right angle? (Accenture)
No. The sum of angles in a triangle is always 180°, and two right angles would exceed that.
6. How do floating-point inaccuracies affect the check? (Wipro)
Small errors may occur in square root or exponentiation, so comparisons should use tolerance.
7. Is (5, 12, 13) a right-angled triangle? Prove it. (IBM)
Yes. 5² + 12² = 25 + 144 = 169 = 13².
8. What happens if all three sides are equal? (HCL)
It’s an equilateral triangle, not right-angled; no angle is 90°.
9. Can a triangle be both isosceles and right-angled? (Tech Mahindra)
Yes. A triangle with two equal sides and a 90° angle is possible, like (1, 1, √2).
10. What is the unit of measurement for sides? (Mindtree)
Sides can be in any unit (cm, m, etc.), but all must be in the same unit for correct comparison.

67

You might also like