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

Python Practical File

semester 3 bca

Uploaded by

shagunverma504
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
33 views

Python Practical File

semester 3 bca

Uploaded by

shagunverma504
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 35

PRACTICAL FILE

PYTHON PROGRAMMING
SUBJECT CODE – BCA 211

Submitted by:- Submitted to :-

Shagun Verma Mr. Harjender Singh


03221202023 [Asst. Prof.]

DEPARTMENT OF COMPUTER APPLICATION


MAHARAJA SURAJMAL INSTITUTE
(Affiliated to GGSIP University & NAAC ‘A’ grade accredited)

C4, Janakpuri New Delhi – 58


INDEX [UNIT – 1]
S. TOPIC SI
N G
O N
1. WAP TO FIND THE AREA OF A
RECTANGLE GIVEN ITS LENGTH IS 10
UNITS AND BREADTH IS 20 UNITS
2. WAP TO FIND THE SUM OF TWO
NUMBERS
3. WAP TO DISPLAY ALL THE
KEYWORDS IN PYTHON
WAP TO IMPLEMENT MULTILINE
4. STRINGS
WAP TO IMPLEMENT ESCAPE
5. CHARACTERS
WAP TO CREATE A LIST AND
6. PERFORM OPERATIONS ON LIST
a)ACCESS ELEMENTS STORED AT
INDEX 3,6,9
b)DELETE ELEMENTS FROM INDEX
2,4,6

2
c)APPEND SOME NEW
ELEMENTS(create empty list)
d)APPEND NEW ELEMENT THROUGH
ITERATION
WAP TO CREATE SET,TUPLES AND
7. DICTIONARY (store 7 elements each)
WAP TO CALCULATE THE LENGTH
8. OF EACH DATA TYPE
WAP TO DEMONSTRATE MUTABLE
9. AND IMMUTABLE TYPE WITH
EXAMPLES
10 WAP TO CALCULATE THE SUM OF
. NUMBERS UNTIL THE USER ENTERS
ZERO
11 WAP TO CREATE THE
. MULTIPLICATION TABLE OF ANY
NUMBER
12 WRITE A NESTED FOR LOOP
. PROGRAM TO PRINT
MULTIPLICATION TABLE IN PYTHON
13 WAP TO PRINT VARIOUS PATTERN
.

3
14 WAP TO PRINT RECTANGLE
. PATTERN WITH 5 ROWS AND 3
COLUMNS OF STARS
WAP TO PRINT ALL PERFECT
15 NUMBERS FROM 1 TO 100
.
WAP TO IMPLEMENT VARIOUS
16 STRING FUNCTIONS
. (lower(),upper(),count(),title(),capitalize()
,find(),index(),isalpha(),isdigit(),isalnum()
)
WAP TO IMPLEMENT SWAP
17 FUNCTIONS BY DIFFERENT
. METHODS
a)using a temporary variable
b)without using a temporary variable
c)addition and subtraction
d)multiplication and division
e)XOR swap

4
PRACTICAL-1
Question 1: WAP TO FIND THE AREA OF A RECTANGLE GIVEN ITS LENGTH IS
10 UNITS AND BREADTH IS 20 UNITS
CODE:
# Calculate the area of a rectangle
length = 10
breadth = 20

area = length * breadth

print(f"The area of the rectangle is {area} square


units.")

OUTPUT:
The area of the rectangle is 200 square units.

5
PRACTICAL-2
Question 2: WAP TO FIND THE SUM OF TWO NUMBERS
CODE:
# Input two numbers
num1 = float(input("Enter the first number: "))
num2 = float(input("Enter the second number: "))

# Calculate the sum


sum_result = num1 + num2

print(f"The sum of {num1} and {num2} is


{sum_result}.")

OUTPUT:
Enter the first number: 2
Enter the second number: 3
The sum of 2.0 and 3.0 is 5.0.

6
PRACTICAL-3
Question 3: WAP TO DISPLAY ALL THE KEYWORDS IN PYTHON

CODE:
import keyword

# Get a list of all Python keywords


all_keywords = keyword.kwlist

# Display the keywords


print("Python Keywords:")
for kw in all_keywords:
print(kw)

OUTPUT:
Python Keywords:
False
None
True
and
as
assert
async
await
break
class
continue
def

7
del
elif
else
except
finally
for
from
global
if
import
in
is
lambda
nonlocal
not
or
pass
raise
return
try
while
with
yield

8
PRACTICAL-4
Question 4: WAP TO IMPLEMENT MULTILINE STRINGS

CODE:
multiline_string = '''
This is a multiline string.
It can span multiple lines.
You can include line breaks and special characters
here.
'''

print(multiline_string)

OUTPUT:
This is a multiline string.
It can span multiple lines.
You can include line breaks and special characters
here.

9
PRACTICAL-5
Question 5: WAP TO IMPLEMENT ESCAPE CHARACTERS

CODE:
# Newline and tab
print("Hello\nWorld")
print("Python\tProgramming")

# Escaping quotes
print('She said, "Hello!"')
print("He's learning Python.")

# Backslash
print("This is a backslash: \\")

OUTPUT:
Hello
World
Python Programming
She said, "Hello!"
He's learning Python.
This is a backslash: \

10
PRACTICAL-6
Question 6: WAP TO CREATE A LIST AND PERFORM OPERATIONS ON LIST

a)ACCESS ELEMENTS STORED AT INDEX 3,6,9

b)DELETE ELEMENTS FROM INDEX 2,4,6

c)APPEND SOME NEW ELEMENTS(create empty list)

d)APPEND NEW ELEMENT THROUGH ITERATION

CODE:
# Create an initial list
my_list = [10, 20, 30, 40, 50, 60, 70, 80, 90]

# Access elements at specific indices (if they exist)


if len(my_list) > 3:
element_at_3 = my_list[3]
else:
element_at_3 = None

if len(my_list) > 6:
element_at_6 = my_list[6]
else:
element_at_6 = None

if len(my_list) > 9:
element_at_9 = my_list[9]
else:
element_at_9 = None

11
print(f"Element at index 3: {element_at_3}")
print(f"Element at index 6: {element_at_6}")
print(f"Element at index 9: {element_at_9}")

# Delete elements from specific indices (if they


exist)
if len(my_list) > 2:
del my_list[2] # Delete element at index 2

if len(my_list) > 4:
del my_list[4] # Delete element at index 4

if len(my_list) > 6:
del my_list[6] # Delete element at index 6

print("List after deletion:")


print(my_list)

# Append new elements (create an empty list)


new_list = []

# Append elements through iteration


for i in range(5):
new_element = int(input(f"Enter element {i+1}:
"))
new_list.append(new_element)

print("New list after appending elements:")

12
print(new_list)

OUTPUT:
Element at index 3: 40
Element at index 6: 70
Element at index 9: None
List after deletion:
[10, 20, 40, 50, 70, 80]
Enter element 1:

13
PRACTICAL-7
Question 7: WAP TO CREATE SET,TUPLES AND DICTIONARY (store 7 elements
each)

CODE:
# Create a set with 7 elements
my_set = {10, 20, 30, 40, 50, 60, 70}
print("Set:", my_set)
# Create a tuple with 7 elements
my_tuple = (100, 200, 300, 400, 500, 600, 700)
print("Tuple:", my_tuple)
# Create a dictionary with 7 key-value pairs
my_dict = {'apple': 3,'banana': 5,'cherry': 2,'date':
4,'elderberry': 1,'fig': 6,'grape': 7}
print("Dictionary:", my_dict)

OUTPUT:
Set: {50, 20, 70, 40, 10, 60, 30}
Tuple: (100, 200, 300, 400, 500, 600, 700)
Dictionary: {'apple': 3, 'banana': 5, 'cherry': 2,
'date': 4, 'elderberry': 1, 'fig': 6, 'grape': 7}

14
PRACTICAL-8
Question 8: WAP TO CALCULATE THE LENGTH OF EACH DATA TYPE

CODE:
# Calculate lengths for different data types
my_string = "Hello, World!"
my_list = [1, 2, 3, 4, 5]
my_tuple = (10, 20, 30, 40, 50)
my_dict = {"a": 1, "b": 2, "c": 3}
my_set = {1, 2, 3, 4, 5}

# Display the results


print(f"String length: {len(my_string)}")
print(f"List length: {len(my_list)}")
print(f"Tuple length: {len(my_tuple)}")
print(f"Dictionary length: {len(my_dict)}")
print(f"Set length: {len(my_set)}"))
OUTPUT:
String length: 13
List length: 5
Tuple length: 5
Dictionary length: 3
Set length: 5

15
PRACTICAL-9
Question 9: WAP TO DEMONSTRATE MUTABLE AND IMMUTABLE TYPE WITH
EXAMPLES

CODE:
# Immutable data types
my_string = "Hello, World!" # String (immutable)
my_tuple = (10, 20, 30) # Tuple (immutable)
# Mutable data types
my_list = [1, 2, 3] # List (mutable)
my_dict = {"a": 1, "b": 2} # Dictionary (mutable)
my_set = {1, 2, 3} # Set (mutable)
# Modify mutable objects
my_list.append(4)
my_dict["c"] = 3

print(f"String: {my_string}")
print(f"Tuple: {my_tuple}")
print(f"List: {my_list}")
print(f"Dictionary: {my_dict}")
print(f"Set: {my_set}")

OUTPUT:
String: Hello, World!
Tuple: (10, 20, 30)
List: [1, 2, 3, 4]
Dictionary: {'a': 1, 'b': 2, 'c': 3}
Set: {1, 2, 3}

16
PRACTICAL-10
Question 10: WAP TO CALCULATE THE SUM OF NUMBERS UNTIL THE USER
ENTERS ZERO

CODE:
total_sum = 0
while True:
try:
user_input = float(input("Enter a number (or
0 to stop): "))
if user_input == 0:
break
total_sum += user_input
except ValueError:
print("Invalid input. Please enter a valid
number.")
print(f"Sum of the entered numbers: {total_sum}")

OUTPUT:
Enter a number (or 0 to stop): 2
Enter a number (or 0 to stop): 22
Enter a number (or 0 to stop): 222
Enter a number (or 0 to stop): 0
Sum of the entered numbers: 246.0

17
PRACTICAL-11
Question 11: WAP TO CREATE THE MULTIPLICATION TABLE OF ANY
NUMBER.
CODE:
num = int(input("Enter a number: "))
for i in range(1, 11):
print(f"{num} × {i} = {num * i}")

OUTPUT:
Enter a number: 5
5 × 1 = 5
5 × 2 = 10
5 × 3 = 15
5 × 4 = 20
5 × 5 = 25
5 × 6 = 30
5 × 7 = 35
5 × 8 = 40
5 × 9 = 45
5 × 10 = 50

18
PRACTICAL-12
Question 12: WRITE A NESTED FOR LOOP PROGRAM TO PRINT
MULTIPLICATION TABLE IN PYTHON

CODE:
# Outer loop for rows (1 to 10)
for i in range(1, 11):
# Nested loop for columns (1 to 10)
for j in range(1, 11):
# Print the product of i and j
print(i * j, end=' ')
# Move to the next row
print() # Print a newline after each row
OUTPUT:
1 2 3 4 5 6 7 8 9 10
2 4 6 8 10 12 14 16 18 20
3 6 9 12 15 18 21 24 27 30
4 8 12 16 20 24 28 32 36 40
5 10 15 20 25 30 35 40 45 50
6 12 18 24 30 36 42 48 54 60
7 14 21 28 35 42 49 56 63 70
8 16 24 32 40 48 56 64 72 80
9 18 27 36 45 54 63 72 81 90
10 20 30 40 50 60 70 80 90 100

19
PRACTICAL-13
Question 13: WAP TO PRINT VARIOUS PATTERN

CODE:
rows = 5
for i in range(1, rows + 1):
print(" " * (rows - i) + "*" * (2 * i - 1))
rows = 5
for i in range(rows, 0, -1):
print(" " * (rows - i) + str(i) * (2 * i - 1))
rows = 5
for i in range(1, rows + 1):
print(" " * (rows - i) + chr(64 + i) * (2 * i -
1))

OUTPUT:

*
***
*****
*******
*********

555555555
4444444
33333
222
1

20
A
BBB
CCCCC
DDDDDDD
EEEEEEEEE

21
PRACTICAL-14
Question 14: WAP TO PRINT RECTANGLE PATTERN WITH 5 ROWS
AND 3 COLUMNS OF STARS.

CODE:
rows = 5
columns = 3

for i in range(rows):
print("*" * columns)

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

22
PRACTICAL-15
Question 15: WAP TO PRINT ALL PERFECT NUMBERS FROM 1 TO
100

CODE:
# Python program to print perfect numbers from 1 to
100
def perfect_Number(n):
if n < 1:
return False
perfect_sum = 0
for i in range(1, n):
if n % i == 0:
perfect_sum += i
return perfect_sum == n

min_value = 1
max_value = 100
print(f"Perfect numbers from {min_value} to
{max_value} are:")
for i in range(min_value, max_value + 1):
if perfect_Number(i):
print(i, end=', ')
OUTPUT:
Perfect numbers from 1 to 100 are: 6, 28,

23
PRACTICAL-16
Question 16 : WAP TO IMPLEMENT VARIOUS STRING FUNCTIONS
(lower(),upper(),count(),title(),capitalize(),find(),index(),isalpha(),isdigit(),is
alnum()).
CODE:
def demonstrate_string_functions():
original_string = "Hello, World!"

# 1. lower()
lower_case_string = original_string.lower()
print(f"Lowercase: {lower_case_string}")

# 2. upper()
upper_case_string = original_string.upper()
print(f"Uppercase: {upper_case_string}")

# 3. count(substring)
count_a = original_string.count("o")
print(f"Count of 'o': {count_a}")

# 4. title()
title_string = original_string.title()
print(f"Title case: {title_string}")

# 5. capitalize()
capitalized_string = original_string.capitalize()
print(f"Capitalized: {capitalized_string}")

24
# 6. find(substring)
index_world = original_string.find("World")
print(f"Index of 'World': {index_world}")

# 7. index(substring)
try:
index_hello = original_string.index("Hello")
print(f"Index of 'Hello': {index_hello}")
except ValueError:
print("Substring not found.")

# 8. isalpha()
print(f"Is alphabetic?
{original_string.isalpha()}")

# 9. isdigit()
numeric_string = "12345"
print(f"Is numeric? {numeric_string.isdigit()}")

# 10. isalnum()
alnum_string = "Hello123"
print(f"Is alphanumeric?
{alnum_string.isalnum()}")

# Call the function to demonstrate the string


functions
demonstrate_string_functions()

25
OUTPUT:
Lowercase: hello, world!
Uppercase: HELLO, WORLD!
Count of 'o': 2
Title case: Hello, World!
Capitalized: Hello, world!
Index of 'World': 7
Index of 'Hello': 0
Is alphabetic? False
Is numeric? True
Is alphanumeric? True

26
PRACTICAL-17
Question 17: WAP TO IMPLEMENT SWAP FUNCTIONS BY
DIFFERENT METHODS

a)using a temporary variable

b)without using a temporary variable

c)addition and subtraction

d)multiplication and division

e)XOR swap

CODE:
def swap_without_temp(a, b):
a = a + b
b = a - b
a = a - b
return a, b
x, y = 10, 20
x, y = swap_without_temp(x, y)
print(f"Swapped values (without temp): x = {x}, y =
{y}")

def swap_add_sub(a, b):


a = a + b
b = a - b
a = a - b
return a, b
x, y = 10, 20

27
x, y = swap_add_sub(x, y)
print(f"Swapped values (add/sub): x = {x}, y = {y}")

def swap_mul_div(a, b):


a = a * b
b = a / b
a = a / b
return a, b
x, y = 10, 20
x, y = swap_mul_div(x, y)
print(f"Swapped values (mul/div): x = {x}, y = {y}")

def xor_swap(a, b):


a = a ^ b
b = a ^ b
a = a ^ b
return a, b
x, y = 10, 20
x, y = xor_swap(x, y)
print(f"Swapped values (XOR): x = {x}, y = {y}")

28
OUTPUT:
Swapped values (without temp): x = 20, y = 10
Swapped values (add/sub): x = 20, y = 10
Swapped values (mul/div): x = 20.0, y = 10.0
Swapped values (XOR): x = 20, y = 10

29
INDEX
[UNIT-2]
No. Practical Question Teacher’s
Sign

1. WAP to display the squares of all positive even


numbers entered by the user. The program
should continue as long as the user wants but
should terminate when the user enters a zero
or a negative number.

2. Write a program which prompts the user for


10 floating-point numbers and calculates their
sum, product and average. Your program
should only contain a single loop. Rewrite the
previous program so that it has two loops – one
which collects and stores the numbers, and one
which processes them.

Create a list of 5 names- Anil, amol,


3. Aditya,avi,alka
1. Insert a name Anuj, before Aditya
2. Append a name Zulu
3. Sort all the names in the list
4. Print reversed sorted list

30
PRACTICAL-1
Question: WAP to display the squares of all positive even numbers
entered by the user. The program should continue as long as the
user wants but should terminate when the user enters a zero or a
negative number.
CODE:
def main():
while True:
try:
num = int(input("Enter a positive integer
(or zero/negative to exit): "))
if num <= 0:
break # Exit the loop if zero or
negative input
elif num % 2 == 0:
print(f"The square of {num} is
{num**2}")
else:
print(f"{num} is not an even
number.")
except ValueError:
print("Invalid input. Please enter a
valid positive integer.")

if __name__ == "__main__":
main()

31
OUTPUT:

Enter a positive integer (or zero/negative to exit):


1
1 is not an even number.
Enter a positive integer (or zero/negative to exit):
0

32
PRACTICAL-2
Question: Write a program which prompts the user for 10 floating-point
numbers and calculates their sum, product and average. Your program
should only contain a single loop. Rewrite the previous program so that it
has two loops – one which collects and stores the numbers, and one which
processes them.

CODE:
def main_two_loops():
total_numbers = 10
numbers = [] # List to store the collected
numbers

# Collect the numbers


for i in range(total_numbers):
try:
num = float(input(f"Enter number {i + 1}:
"))
numbers.append(num)
except ValueError:
print("Invalid input. Please enter a
valid floating-point number.")

# Process the collected numbers


sum_numbers = sum(numbers)
product_numbers = 1.0
for num in numbers:
product_numbers *= num

33
average = sum_numbers / total_numbers

print(f"Sum: {sum_numbers:.2f}")
print(f"Product: {product_numbers:.2f}")
print(f"Average: {average:.2f}")

if __name__ == "__main__":
main_two_loops()

OUTPUT:
Enter number 1: 1
Enter number 2: 2
Enter number 3: 3
Enter number 4: 4.5
Enter number 5: 6
Enter number 6: 7
Enter number 7: 8
Enter number 8: 9
Enter number 9: 1.0
Enter number 10: 2.0
Sum: 43.50
Product: 163296.00
Average: 4.35

34
PRACTICAL-3
Question: Create a list of 5 names- Anil, amol, Aditya,avi,alka

1. Insert a name Anuj, before Aditya


2. Append a name Zulu
3. Sort all the names in the list
4. Print reversed sorted list
CODE:
names_list = ["Anil", "Amol", "Aditya", "Avi",
"Alka"]
names_list.insert(names_list.index("Aditya"), "Anuj")
names_list.append("Zulu")
names_list.sort()
print("Reversed Sorted Names:")
for name in reversed(names_list):
print(name)

OUTPUT:
Reversed Sorted Names:

Zulu
Avi
Anuj
Anil
Amol
Alka

35

You might also like