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

Python Programming Lab Exercises

The document outlines a Python programming lab for B.Tech first-year students, detailing various programming tasks with corresponding code examples and expected outputs. The tasks include displaying student details, checking even/odd numbers, finding the greatest of three numbers, checking Armstrong numbers, calculating factorials, generating patterns, counting characters in a string, multiplying list numbers, finding averages, and demonstrating object-oriented programming concepts. Each task is accompanied by sample code and output to illustrate the expected results.

Uploaded by

shivashishp0
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 views27 pages

Python Programming Lab Exercises

The document outlines a Python programming lab for B.Tech first-year students, detailing various programming tasks with corresponding code examples and expected outputs. The tasks include displaying student details, checking even/odd numbers, finding the greatest of three numbers, checking Armstrong numbers, calculating factorials, generating patterns, counting characters in a string, multiplying list numbers, finding averages, and demonstrating object-oriented programming concepts. Each task is accompanied by sample code and output to illustrate the expected results.

Uploaded by

shivashishp0
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

Pythion programming lab

PCS 151
[Link] First Year
2025-26 (ODD SEM)

Aim 1: Write a program to display student’s details


Code:
# Student Details Program without using functions

# Input details for three students


student1_name = input("Enter name of student 1: ")
student1_age = int(input("Enter age of student 1: "))
student1_grade = input("Enter grade of student 1: ")
student2_name = input("\nEnter name of student 2: ")
student2_age = int(input("Enter age of student 2: "))
student2_grade = input("Enter grade of student 2: ")
student3_name = input("\nEnter name of student 3: ")
student3_age = int(input("Enter age of student 3: "))
student3_grade = input("Enter grade of student 3: ")
# Displaying student details
print("\nStudent Details:")
print(f"Student 1 - Name: {student1_name}, Age: {student1_age}, Grade:
{student1_grade}")
print(f"Student 2 - Name: {student2_name}, Age: {student2_age}, Grade:
{student2_grade}")
print(f"Student 3 - Name: {student3_name}, Age: {student3_age}, Grade:
{student3_grade}")

Output: -
Student Details:
Student 1 - Name: akshay, Age: 19, Grade: A
Student 2 - Name: Abhishek, Age: 20, Grade: B+
Student 3 - Name: Ankit, Age: 20, Grade: B++
Aim: -2 Write a program to check given number is even or odd
Code:-
num = int(input("Enter a number: "))
if (num%2==0):
print("This is even number")
else:
print("This is Odd Number")

Output: -
Enter a number: 4
This is even number
Aim: -3 Write a program to find the greatest of three numbers (use
only if statement)
Code:
num1 = 10
num2 = 14
num3 = 12
if (num1 >= num2) and (num1 >= num3):
largest = num1
elif (num2 >= num1) and (num2 >= num3):
largest = num2
else:
largest = num3

print("The largest number is", largest)

Output: -
The largest number is 14
Aim: -4 Write a program in Python to check whether a given number
is Armstrong.
Code:
def is_armstrong_number(number):
# Convert the number to a string to find its length
num_str = str(number)
num_digits = len(num_str)

# Calculate the sum of each digit raised to the power of the number of
digits
armstrong_sum = sum(int(digit) ** num_digits for digit in num_str)

# Check if the sum is equal to the original number


return armstrong_sum == number

# Example usage
user_input = int(input("Enter a number to check if it's an Armstrong
number: "))

if is_armstrong_number(user_input):
print(f"{user_input} is an Armstrong number.")
else:
print(f"{user_input} is not an Armstrong number.")

Output: -
Enter a number to check if it's an Armstrong number: 153
153 is an Armstrong number.
Aim: -5 Write a program in python to print factorial of a number
using for loop.
def factorial(n):
# Base case: factorial of 0 or 1 is 1
if n == 0 or n == 1:
return 1
else:
# Recursive case: n! = n * (n-1)!
return n * factorial(n - 1)

# Example usage
user_input = int(input("Enter a number to calculate its factorial: "))

# Check for non-negative input


if user_input < 0:
print("Factorial is not defined for negative numbers.")
else:
result = factorial(user_input)
print(f"The factorial of {user_input} is: {result}")

Output: -
Enter a number to calculate its factorial: 5
The factorial of 5 is: 120
Aim: -6 Write a program in python to print different patterns using
for loop

Code:1) Square Pattern


rows = 5

for i in range(rows):
for j in range(rows):
print("* ", end="")
print()

Output: -
*****
*****
*****
*****
*****

2) Right Angled Triangle


rows = 5

for i in range(1, rows + 1):


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

3) Inverted Right Angled Triangle


rows = 5

for i in range(rows, 0, -1):


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

Output: -
*****
****
***
**
*
4) Hollow Square
rows = 5
for i in range(rows):
for j in range(rows):
if i == 0 or i == rows - 1 or j == 0 or j == rows - 1:
print("* ", end="")
else:
print(" ", end="")
print()

Output: -
*****
* *
* *
* *
*****
Aim: -7 Write a python program to count the number of characters in
a string.
Code:
def count_characters(input_string):
# Using len() function to get the count of characters
char_count = len(input_string)
return char_count

# Example usage
user_input = input("Enter a string: ")

result = count_characters(user_input)
print(f"The number of characters in the string is: {result}")

Output: -
Enter a string: tiwari
The number of characters in the string is: 6
Aim: -8 Write a python program to multiply all the numbers in a list.
Code:
def multiply_list(numbers):
result = 1
for num in numbers:
result *= num
return result

# Example usage
user_input = input("Enter a list of numbers separated by spaces: ")

# Convert the input string to a list of integers


numbers_list = [int(x) for x in user_input.split()]

# Check if the list is not empty


if numbers_list:
result = multiply_list(numbers_list)
print(f"The product of the numbers in the list is: {result}")
else:
print("The list is empty.")

Output: -
Enter a list of numbers separated by spaces: 1 2 3 4 5
The product of the numbers in the list is: 120
Aim: - 9 Write a program to find the average of n numbers from the
given list.
Code:
def calculate_average(numbers):
# Check if the list is not empty
if len(numbers) == 0:
return None

# Calculate the average


average = sum(numbers) / len(numbers)
return average

# Example usage
user_input = input("Enter a list of numbers separated by spaces: ")

# Convert the input string to a list of floats


numbers_list = [float(x) for x in user_input.split()]

# Calculate the average and display the result


result = calculate_average(numbers_list)

if result is not None:


print(f"The average of the numbers in the list is: {result}")
else:
print("The list is empty.")
Output: -
Enter a list of numbers separated by spaces: 6 7 8 9 10
The average of the numbers in the list is: 8.0
Aim: -10 Write a program to find maximum/minimum numbers from
the given list.
Code:
def find_max_min(numbers):
# Check if the list is not empty
if len(numbers) == 0:
return None, None

# Find the maximum and minimum numbers


maximum = max(numbers)
minimum = min(numbers)
return maximum, minimum

# Example usage
user_input = input("Enter a list of numbers separated by spaces: ")

# Convert the input string to a list of floats


numbers_list = [float(x) for x in user_input.split()]

# Find the maximum and minimum numbers and display the result
max_num, min_num = find_max_min(numbers_list)

if max_num is not None and min_num is not None:


print(f"The maximum number in the list is: {max_num}")
print(f"The minimum number in the list is: {min_num}")
else:
print("The list is empty.")

Output: -
Enter a list of numbers separated by spaces: 3 4 5 6 7
The maximum number in the list is: 7.0
The minimum number in the list is: 3.0
Aim: - 11 Write a program to demonstrate different argument
(positional, default, keyword) pass to function.
Code:
def example_function(positional_arg, default_arg="default_value", *args,
**kwargs):
"""
Function to demonstrate different types of arguments.
"""
print("Positional Argument:", positional_arg)
print("Default Argument:", default_arg)
print("Additional Positional Arguments (*args):", args)
print("Additional Keyword Arguments (**kwargs):", kwargs)
print()

# Example usage
example_function("Positional Argument")

example_function("Positional Argument", "Custom Default Value")

example_function("Positional Argument", "Custom Default Value", 1, 2,


3)

example_function("Positional Argument", custom_kwarg1="Value1",


custom_kwarg2="Value2")
Output: -
Positional Argument: Positional Argument
Default Argument: default_value
Additional Positional Arguments (*args): ()
Additional Keyword Arguments (**kwargs): {}

Positional Argument: Positional Argument


Default Argument: Custom Default Value
Additional Positional Arguments (*args): ()
Additional Keyword Arguments (**kwargs): {}

Positional Argument: Positional Argument


Default Argument: Custom Default Value
Additional Positional Arguments (*args): (1, 2, 3)
Additional Keyword Arguments (**kwargs): {}

Positional Argument: Positional Argument


Default Argument: default_value
Additional Positional Arguments (*args): ()
Additional Keyword Arguments (**kwargs): {'custom_kwarg1': 'Value1',
'custom_kwarg2': 'Value2'}
Aim: - 12 Write a program in python to generate first n Fibonacci
terms using recursive function.
Code:
def fibonacci_recursive(n):
# Base case: return 0 for the first term
if n == 0:
return 0
# Base case: return 1 for the second term
elif n == 1:
return 1
else:
# Recursive case: F(n) = F(n-1) + F(n-2)
return fibonacci_recursive(n - 1) + fibonacci_recursive(n - 2)

# Example usage
try:
n = int(input("Enter the number of Fibonacci terms to generate: "))
if n < 0:
raise ValueError("Please enter a non-negative integer.")

fibonacci_sequence = [fibonacci_recursive(i) for i in range(n)]

print(f"The first {n} Fibonacci terms are: {fibonacci_sequence}")


except ValueError as e:
print(f"Error: {e}")
Output: -
Enter the number of Fibonacci terms to generate: 5
The first 5 Fibonacci terms are: [0, 1, 1, 2, 3]
Aim: - 13 Program to illustrate the concept of class and objects in
python.
Code:
class Dog:
# Class variable
species = "Canis familiaris"

# Constructor or initializer method


def __init__(self, name, age):
# Instance variables
[Link] = name
[Link] = age

# Instance method
def bark(self):
return "Woof!"

# Creating objects (instances) of the Dog class


dog1 = Dog(name="Buddy", age=2)
dog2 = Dog(name="Max", age=3)

# Accessing attributes and calling methods of the objects


print(f"{[Link]} is {[Link]} years old.")
print(f"{[Link]} is {[Link]} years old.")
print(f"{[Link]} says: {[Link]()}")
print(f"{[Link]} says: {[Link]()}")

# Accessing class variable


print(f"They both belong to the species {[Link]}.")

Output: -
Buddy is 2 years old.
Max is 3 years old.
Buddy says: Woof!
Max says: Woof!
They both belong to the species Canis familiaris.
Aim: -14 Program to illustrate the concept of inheritance in python.
Code:
# Parent class (base class)
class Animal:
def __init__(self, name):
[Link] = name

def speak(self):
return "Some generic sound"

# Child class (derived class) inheriting from Animal


class Dog(Animal):
def __init__(self, name, breed):
# Call the constructor of the parent class
super().__init__(name)
# Additional attribute specific to Dog class
[Link] = breed

# Override the speak method of the parent class


def speak(self):
return "Woof!"

# Child class (derived class) inheriting from Animal


class Cat(Animal):
def __init__(self, name, color):
# Call the constructor of the parent class
super().__init__(name)
# Additional attribute specific to Cat class
[Link] = color

# Override the speak method of the parent class


def speak(self):
return "Meow!"

# Creating objects (instances) of the derived classes


dog_instance = Dog(name="Buddy", breed="Labrador")
cat_instance = Cat(name="Whiskers", color="Calico")

# Accessing attributes and calling methods of the objects


print(f"{dog_instance.name} is a {dog_instance.breed} and says:
{dog_instance.speak()}")
print(f"{cat_instance.name} is {cat_instance.color} and says:
{cat_instance.speak()}")

Output: -
Buddy is a Labrador and says: Woof!
Whiskers is Calico and says: Meow!
Aim: -15 Program to illustrate the concept of method overriding in
python.
Code:
# Parent class (base class)
class Animal:
def speak(self):
return "Some generic sound"

# Child class (derived class) inheriting from Animal


class Dog(Animal):
def speak(self):
return "Woof!"

# Child class (derived class) inheriting from Animal


class Cat(Animal):
def speak(self):
return "Meow!"

# Creating objects (instances) of the derived classes


dog_instance = Dog()
cat_instance = Cat()

# Calling the overridden speak method for each object


print("Dog says:", dog_instance.speak())
print("Cat says:", cat_instance.speak())
Output: -
Dog says: Woof!
Cat says: Meow!
Aim: -16 Write a program to create a file in write mode and add some
contents into it and display the output.
Code:
# Open a file in write mode ('w')
file_path = "sample_file.txt"

# Writing content to the file


with open(file_path, 'w') as file:
[Link]("Hello, this is some content for the file.\n")
[Link]("Adding another line for demonstration.\n")

# Reading and displaying the content of the file


with open(file_path, 'r') as file:
file_content = [Link]()
print("Content of the file:")
print(file_content)

Output: -
Content of the file:
Hello, this is some content for the file.
Adding another line for demonstration.

You might also like