S.S.and S.
S’s
Vidhydhan Commerce college Wadel Road Dhule
Department of Computer Science
Class :- SYBCA Sem-III Subject BCA307(c) Lab on Python
Student Name :-
Practical 1A:- Print Hellow Word
********************************************************************************************************
print("hellow World")
Output
S.S.and S.S’s
Vidhydhan Commerce college Wadel Road Dhule
Department of Computer Science
Class :- SYBCA Sem-III Subject BCA307(c) Lab on Python
Student Name :-
Practical 1B:- mathematical calculations
************************************************************************
num1 = int (input('Enter first number: '))
num2 = int (input('Enter second number: '))
add = num1+num2
print("the addition of two number is ====>",add)
print("=======================================")
sub = num1 - num2
print("the addition of two number is ====>",sub)
print("=======================================")
mul = num1 * num2
print("the addition of two number is ====>",mul)
print("=======================================")
div = num1 / num2
print("the addition of two number is ====>",div)
print("=======================================")
OUTPUT
S.S.and S.S’s
Vidhydhan Commerce college Wadel Road Dhule
Department of Computer Science
Class :- SYBCA Sem-III Subject BCA307(c) Lab on Python
Student Name :-
Practical 2:- Write a program to find all prime numbers within a given range
***********************************************************************
# First, we will take the input:
lower_value = int(input ("Please, Enter the Lowest Range Value: "))
upper_value = int(input ("Please, Enter the Upper Range Value: "))
print ("The Prime Numbers in the range are: ")
for number in range (lower_value, upper_value + 1):
if number > 1:
for i in range (2, number):
if (number % i) == 0:
break
else:
print (number)
OUTPUT
S.S.and S.S’s
Vidhydhan Commerce college Wadel Road Dhule
Department of Computer Science
Class :- SYBCA Sem-III Subject BCA307(c) Lab on Python
Student Name :-
Practical 3 write a program to print "n" terms of Fibonacci Series using Iteration
*************************************************************************
# Program to display the Fibonacci sequence up to n-th term
nterms = int(input("How many terms? "))
# first two terms
n1, n2 = 0, 1
count = 0
# check if the number of terms is valid
if nterms <= 0:
print("Please enter a positive integer")
# if there is only one term, return n1
elif nterms == 1:
print("Fibonacci sequence upto",nterms,":")
print(n1)
# generate fibonacci sequence
else:
print("Fibonacci sequence:")
while count < nterms:
print(n1)
nth = n1 + n2
# update values
n1 = n2
n2 = nth
count += 1
OUTPUT
S.S.and S.S’s
Vidhydhan Commerce college Wadel Road Dhule
Department of Computer Science
Class :- SYBCA Sem-III Subject BCA307(c) Lab on Python
Student Name :-
Practical 4 write a program to demonstrate the use of slicing in string.
*************************************************************************
# Python program to demonstrate
# string slicing
# String slicing
String = 'ASTRING'
# Using slice constructor
s1 = slice(3)
s2 = slice(1, 5, 2)
s3 = slice(-1, -12, -2)
print("String slicing")
print(String[s1])
print(String[s2])
print(String[s3])
OUTPUT
S.S.and S.S’s
Vidhydhan Commerce college Wadel Road Dhule
Department of Computer Science
Class :- SYBCA Sem-III Subject BCA307(c) Lab on Python
Student Name :-
Practical 5:-Write a Program related to Functions & Modules
*************************************************************************
# importing a module
import math
# using the sqrt() function of the math module
print("Square root of 16:", math.sqrt(16))
OUTPUT
S.S.and S.S’s
Vidhydhan Commerce college Wadel Road Dhule
Department of Computer Science
Class :- SYBCA Sem-III Subject BCA307(c) Lab on Python
Student Name :-
Practical 5B:- Modul
***************************************************************************************
# defining a function
def my_func():
print("Greetings User! Welcome to Javatpoint.")
# calling the function
my_func()
S.S.and S.S’s
Vidhydhan Commerce college Wadel Road Dhule
Department of Computer Science
Class :- SYBCA Sem-III Subject BCA307(c) Lab on Python
Student Name :-
Practical 6 Write a program that demonstrate concept of Functional Programming
**********************************************************************
from functools import reduce
# Sample list of numbers
numbers = [1, 2, 3, 4, 5]
# Function to square a number
def square(x):
return x * x
# Function to check if a number is even
def is_even(x):
return x % 2 == 0
# Function to calculate the sum of a list of numbers
def add(x, y):
return x + y
# Using the map function to square each number in the list
squared_numbers = list(map(square, numbers))
print("Squared numbers:", squared_numbers)
# Using the filter function to filter out even numbers from the list
even_numbers = list(filter(is_even, numbers))
print("Even numbers:", even_numbers)
# Using the reduce function to calculate the sum of all numbers in the list
total = reduce(add, numbers)
print("Total sum:", total)
OUTPUT
S.S.and S.S’s
Vidhydhan Commerce college Wadel Road Dhule
Department of Computer Science
Class :- SYBCA Sem-III Subject BCA307(c) Lab on Python
Student Name :-
Practical 7 Write a program to demonstrate the use of list & related functions.
***********************************************************************
# Creating a list of fruits
fruits = ["apple", "banana", "cherry", "date", "fig"]
# 1. Accessing elements in a list
print("Accessing elements:")
print("First fruit:", fruits[0])
print("Last fruit:", fruits[-1])
print("Slicing a portion:", fruits[1:3])
# 2. Modifying elements in a list
print("\nModifying elements:")
fruits[1] = "grape"
print("Updated list:", fruits)
# 3. Adding elements to a list
print("\nAdding elements:")
fruits.append("kiwi")
print("After appending:", fruits)
# 4. Removing elements from a list
print("\nRemoving elements:")
removed_fruit = fruits.pop(3)
print("Removed fruit:", removed_fruit)
del fruits[0]
print("After deleting:", fruits)
# 5. Finding the length of a list
print("\nFinding the length:")
num_fruits = len(fruits)
print("Number of fruits:", num_fruits)
# 6. Checking if an element is in the list
print("\nChecking for an element:")
if "apple" in fruits:
print("Apple is in the list.")
else:
print("Apple is not in the list.")
# 7. Sorting a list
print("\nSorting the list:")
fruits.sort()
print("Sorted list:", fruits)
# 8. Reversing a list
print("\nReversing the list:")
fruits.reverse()
print("Reversed list:", fruits)
# 9. Copying a list
print("\nCopying the list:")
fruits_copy = fruits.copy()
print("Copied list:", fruits_copy)
# 10. Clearing a list
print("\nClearing the list:")
fruits.clear()
print("Cleared list:", fruits)
OUTPUT
S.S.and S.S’s
Vidhydhan Commerce college Wadel Road Dhule
Department of Computer Science
Class :- SYBCA Sem-III Subject BCA307(c) Lab on Python
Student Name :-
Practical 8. Write a program to demonstrate the use of Dictionary & related functions
********************************************************************
# Creating a dictionary
student_info = {
'name': 'John',
'age': 20,
'grade': 'A',
'courses': ['Math', 'Science', 'English']
}
# Accessing dictionary elements
print("Student Name:", student_info['name'])
print("Student Age:", student_info['age'])
print("Student Grade:", student_info['grade'])
# Modifying dictionary elements
student_info['age'] = 21 # Update age
student_info['courses'].append('History') # Add a course
# Adding new key-value pairs to the dictionary
student_info['address'] = '123 Main St'
# Deleting a key-value pair from the dictionary
del student_info['grade']
# Check if a key exists in the dictionary
if 'grade' not in student_info:
print("Grade not found in student_info")
# Iterating through the dictionary
print("\nStudent Information:")
for key, value in student_info.items():
print(f"{key}: {value}")
# Dictionary functions
print("\nNumber of items in the dictionary:", len(student_info))
print("Keys in the dictionary:", student_info.keys())
print("Values in the dictionary:", student_info.values())
# Copying a dictionary
student_info_copy = student_info.copy()
# Clearing the dictionary
student_info.clear()
# Checking the original and copied dictionaries
print("\nOriginal Student Info:", student_info)
print("Copied Student Info:", student_info_copy)
OUTPUT
S.S.and S.S’s
Vidhydhan Commerce college Wadel Road Dhule
Department of Computer Science
Class :- SYBCA Sem-III Subject BCA307(c) Lab on Python
Student Name :-
Practical 9. Write a program to demonstrate the use of Tuple.
**************************************************************************************
# Python program to show how to create a tuple
# Creating an empty tuple
empty_tuple = ()
print("Empty tuple: ", empty_tuple)
# Creating tuple having integers
int_tuple = (4, 6, 8, 10, 12, 14)
print("Tuple with integers: ", int_tuple)
# Creating a tuple having objects of different data types
mixed_tuple = (4, "Python", 9.3)
print("Tuple with different data types: ", mixed_tuple)
# Creating a nested tuple
nested_tuple = ("Python", {4: 5, 6: 2, 8:2}, (5, 3, 5, 6))
print("A nested tuple: ", nested_tuple)
OUTPUT
# Python program to show how to create a tuple having a single element
single_tuple = ("Tuple")
print( type(single_tuple) )
# Creating a tuple that has only one element
single_tuple = ("Tuple",)
print( type(single_tuple) )
# Creating tuple without parentheses
single_tuple = "Tuple",
print( type(single_tuple) )
# Python program to show how to access tuple elements
# Creating a tuple
tuple_ = ("Python", "Tuple", "Ordered", "Collection")
print(tuple_[0])
print(tuple_[1])
# trying to access element index more than the length of a tuple
try:
print(tuple_[5])
except Exception as e:
print(e)
# trying to access elements through the index of floating data type
try:
print(tuple_[1.0])
except Exception as e:
print(e)
# Creating a nested tuple
nested_tuple = ("Tuple", [4, 6, 2, 6], (6, 2, 6, 7))
# Accessing the index of a nested tuple
print(nested_tuple[0][3])
print(nested_tuple[1][1])
S.S.and S.S’s
Vidhydhan Commerce college Wadel Road Dhule
Department of Computer Science
Class :- SYBCA Sem-III Subject BCA307(c) Lab on Python
Student Name :-
Practical 10 Write a program to demonstrate Regular Expression in Python
**************************************************************************************
# Program to extract numbers from a string
import re
string = 'hello 12 hi 89. Howdy 34'
pattern = '\d+'
result = re.findall(pattern, string)
print(result)
import re
string = 'Twelve:12 Eighty nine:89.'
pattern = '\d+'
result = re.split(pattern, string)
print(result)
# Program to remove all whitespaces
import re
# multiline string
string = 'abc 12\
de 23 \n f45 6'
# matches all whitespace characters
pattern = '\s+'
# empty string
replace = ''
new_string = re.sub(pattern, replace, string)
print(new_string)
import re
# multiline string
string = 'abc 12\
de 23 \n f45 6'
# matches all whitespace characters
pattern = '\s+'
replace = ''
new_string = re.sub(r'\s+', replace, string, 1)
print(new_string)
OUTPUT
# Program to remove all whitespaces
import re
# multiline string
string = 'abc 12\
de 23 \n f45 6'
# matches all whitespace characters
pattern = '\s+'
# empty string
replace = ''
new_string = re.subn(pattern, replace, string)
print(new_string)
OUTPUT
S.S.and S.S’s
Vidhydhan Commerce college Wadel Road Dhule
Department of Computer Science
Class :- SYBCA Sem-III Subject BCA307(c) Lab on Python
Student Name :-
Practical 11 Write a program to demonstrate the working of Class and Objects.
**************************************************************************************
# define a class
class Bike:
name = ""
gear = 0
# create object of class
bike1 = Bike()
# access attributes and assign new values
bike1.gear = 11
bike1.name = "Mountain Bike"
print(f"Name: {bike1.name}, Gears: {bike1.gear} ")
OUTPUT
# define a class
class Employee:
# define an attribute
employee_id = 0
# create two objects of the Employee class
employee1 = Employee()
employee2 = Employee()
# access attributes using employee1
employee1.employeeID = 1001
print(f"Employee ID: {employee1.employeeID}")
# access attributes using employee2
employee2.employeeID = 1002
print(f"Employee ID: {employee2.employeeID}")
OUTPUT
S.S.and S.S’s
Vidhydhan Commerce college Wadel Road Dhule
Department of Computer Science
Class :- SYBCA Sem-III Subject BCA307(c) Lab on Python
Student Name :-
Practical 12. Write a program to demonstrate the working of Inheritance
****************************************************************************************
class Animal:
# attribute and method of the parent class
name = ""
def eat(self):
print("I can eat")
# inherit from Animal
class Dog(Animal):
# new method in subclass
def display(self):
# access name attribute of superclass using self
print("My name is ", self.name)
# create an object of the subclass
labrador = Dog()
# access superclass attribute and method
labrador.name = "Rohu"
labrador.eat()
# call subclass method
labrador.display()
OUTPUT
class Polygon:
# Initializing the number of sides
def __init__(self, no_of_sides):
self.n = no_of_sides
self.sides = [0 for i in range(no_of_sides)]
def inputSides(self):
self.sides = [float(input("Enter side "+str(i+1)+" : ")) for i in range(self.n)]
# method to display the length of each side of the polygon
def dispSides(self):
for i in range(self.n):
print("Side",i+1,"is",self.sides[i])
class Triangle(Polygon):
# Initializing the number of sides of the triangle to 3 by
# calling the __init__ method of the Polygon class
def __init__(self):
Polygon.__init__(self,3)
def findArea(self):
a, b, c = self.sides
# calculate the semi-perimeter
s = (a + b + c) / 2
# Using Heron's formula to calculate the area of the triangle
area = (s*(s-a)*(s-b)*(s-c)) ** 0.5
print('The area of the triangle is %0.2f' %area)
# Creating an instance of the Triangle class
t = Triangle()
# Prompting the user to enter the sides of the triangle
t.inputSides()
# Displaying the sides of the triangle
t.dispSides()
# Calculating and printing the area of the triangle
t.findArea()
OUTPUT
S.S.and S.S’s
Vidhydhan Commerce college Wadel Road Dhule
Department of Computer Science
Class :- SYBCA Sem-III Subject BCA307(c) Lab on Python
Student Name :-
Practical 13. Write a program to demonstrate the working of Overloading Methods
****************************************************************************************
class Point:
def __init__(self, x=0, y=0):
self.x = x
self.y = y
def __str__(self):
return "({0},{1})".format(self.x, self.y)
def __add__(self, other):
x = self.x + other.x
y = self.y + other.y
return Point(x, y)
p1 = Point(1, 2)
p2 = Point(2, 3)
print(p1+p2)
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
# overload < operator
def __lt__(self, other):
return self.age < other.age
p1 = Person("Alice", 20)
p2 = Person("Bob", 30)
print(p1 < p2) # prints True
print(p2 < p1) # prints False
S.S.and S.S’s
Vidhydhan Commerce college Wadel Road Dhule
Department of Computer Science
Class :- SYBCA Sem-III Subject BCA307(c) Lab on Python
Student Name :-
Practical 14. Write a program to demonstrate Exception Handling Mechanism
****************************************************************************************
try:
even_numbers = [2,4,6,8]
print(even_numbers[5])
except ZeroDivisionError:
print("Denominator cannot be 0.")
except IndexError:
print("Index Out of Bound.")
# program to print the reciprocal of even numbers
try:
num = int(input("Enter a number: "))
assert num % 2 == 0
except:
print("Not an even number!")
else:
reciprocal = 1/num
print(reciprocal)