Python Lab
Python Lab
Write a Python program to create a list variable with contain six items to slice the
middle two items and display.
Code:
python
# Display results
Output:
less
Question 2
Code:
python
import operator
# Define operator functions
operations = {
'-': operator.sub,
'*': operator.mul,
'/': operator.truediv
# Perform operation
if op in operations:
else:
print("Result:", result)
else:
print("Invalid operator")
Output:
sql
Result: 50.0
Question 3
Write a Python program that checks whether a specified value is contained within a
group of values.
Code:
python
# User input
# Check membership
if val in values:
else:
Output:
pgsql
Question 4
Write a Python menu-driven program to convert the given temperature from
Fahrenheit to Celsius and vice versa depending upon user’s choice.
Code:
python
# Conversion functions
def to_celsius(f):
def to_fahrenheit(c):
return (c * 9/5) + 32
# Menu-driven
if choice == 'C':
else:
print("Invalid choice")
Output:
mathematica
Convert to (C/F): C
Question 5
Code:
python
# Display conversions
print("Decimal:", num)
print("Binary:", bin(num))
print("Octal:", oct(num))
print("Hexadecimal:", hex(num))
Output:
vbnet
Enter an integer: 25
Decimal: 25
Binary: 0b11001
Octal: 0o31
Hexadecimal: 0x19
You said:
ChatGPT said:
Since the answers will be very long, I will post them in manageable batches (5 to 10
questions at a time) so you can review easily.
After I finish all, I will format the entire thing and generate the final PDF document.
Question 6
Write a Python program input three numbers through the user to find out greatest of
three numbers using nested if statements.
Code:
python
if a > b:
if a > c:
else:
else:
if b > c:
else:
Output:
yaml
Question 7
Code:
python
# Example dictionary
# Check presence
if key in my_dict:
else:
Output:
pgsql
Question 8
Code:
python
# Input number
Output:
python-repl
Enter a number: 5
5x1=5
5 x 2 = 10
...
5 x 10 = 50
Question 9
Code:
python
# Input number
# Calculate factorial
fact = 1
fact *= i
# Display result
Output:
mathematica
Enter a number: 5
Factorial of 5 is 120
Question 10
Write a Python program input a number which is any digits to check the number is
Palindrome or not Palindrome.
Code:
python
# Check palindrome
if num == num[::-1]:
print("Palindrome")
else:
print("Not Palindrome")
Output:
css
Palindrome
You said:
continue
ChatGPT said:
Write a Python program input a number to check the number is Prime or not Prime.
Code:
python
# Input number
# Check prime
if num < 2:
print("Not Prime")
else:
if num % i == 0:
print("Not Prime")
break
else:
print("Prime")
Output:
mathematica
Enter a number: 13
Prime
Question 12
Write a Python program input a number which is any digits to check the number is
Armstrong or not Armstrong.
Code:
python
num = int(num_str)
n = len(num_str)
# Check Armstrong
if total == num:
print("Armstrong")
else:
print("Not Armstrong")
Output:
css
Armstrong
Question 13
Code:
python
# Input string
if s == s[::-1]:
print("Palindrome")
else:
print("Not Palindrome")
Output:
csharp
Palindrome
Question 14
Write a Python program input N numbers to calculate sum and average, if found a
negative number then stop the iteration and display the sum and average.
Code:
python
# Input N
# Initialize
nums = []
# Take inputs
for _ in range(N):
if val < 0:
break
nums.append(val)
if nums:
print("Sum:", sum(nums))
else:
Output:
yaml
Enter number: 10
Enter number: 20
Enter number: 30
Enter number: -1
Sum: 60
Average: 20.0
Question 15
Code:
python
# Initialize
a, b = 0, 1
# Print Fibonacci series
print("Fibonacci series:")
for _ in range(10):
a, b = b, a + b
Output:
yaml
Fibonacci series:
0 1 1 2 3 5 8 13 21 34
Shall I proceed?
You said:
yes
ChatGPT said:
Question 16
css
1 54321 A
12 4321 AB
12345 1 ABCDE
Code:
python
# Print pattern
n=5
# Tabs/spaces
print("\t\t", end="")
# Tabs/spaces
print("\t\t", end="")
# Alphabets
Output:
css
1 54321 A
12 4321 AB
12345 1 ABCDE
Question 17
Write a Python program to find out Reverse of a String, Tuple, List and Range.
Code:
python
# String reverse
s = "hello"
# Tuple reverse
t = (1, 2, 3, 4, 5)
# List reverse
# Range reverse
r = range(1, 6)
Output:
pgsql
Question 18
Write a Python program to find out maximum of an integer numbers, floating point
numbers, Characters, Strings and Lists using built-in function.
Code:
python
# Integer
# Float
# Characters
# Strings
# List
Output:
mathematica
Max Integer: 25
Max in List: 50
Question 19
Write a Python program to print current date and time using built-in function.
Code:
python
import datetime
now = datetime.datetime.now()
Output:
sql
Question 20
Write a program in Python to find the day of the week of a given date.
Code:
python
import datetime
# Input date
Output:
sql
Shall I proceed?
You said:
yes
ChatGPT said:
Question 21
Write a program in Python to print current date and time using built-in function.
(Note: This question is same as Question 19, but I will write it again as per the
assignment.)
Code:
python
import datetime
# Current date and time
now = datetime.datetime.now()
Output:
sql
Question 22
Write a program in Python to find the day of the week of a given date.
(Note: This is same as Question 20, repeated in assignment. I will show again.)
Code:
python
import datetime
# Input date
dt = datetime.datetime.strptime(date_str, "%Y-%m-%d")
Output:
sql
Write a Python program that prints the calendar for a given month and year.
Code:
python
import calendar
# Print calendar
print(calendar.month(year, month))
Output:
yaml
June 2025
Mo Tu We Th Fr Sa Su
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30
Question 24
Write a Python program that prints the calendar for a given year.
Code:
python
import calendar
# Input year
# Print calendar
print(calendar.calendar(year))
Output:
yaml
Question 25
Code:
python
import datetime
# Input dates
d1 = datetime.datetime.strptime(date1, "%Y-%m-%d")
d2 = datetime.datetime.strptime(date2, "%Y-%m-%d")
# Calculate difference
Output:
sql
If you reply "Continue", I will proceed with the next batch (Questions 26 to 30).
Once all 46 are done, I will generate the PDF.
Shall I proceed?
You said:
yes
ChatGPT said:
Question 26
Write a Python program to swapping of two numbers with using function with
arguments and no return value.
Code:
python
a, b = b, a
# Input numbers
# Call function
swap(x, y)
Output:
yaml
Before swap: a = 10 , b = 20
After swap: a = 20 , b = 10
Question 27
Write a Python program to calculate number of days between two given dates.
(Note: Same as Question 25 — I will write again as per the assignment.)
Code:
python
import datetime
# Input dates
d1 = datetime.datetime.strptime(date1, "%Y-%m-%d")
d2 = datetime.datetime.strptime(date2, "%Y-%m-%d")
# Calculate difference
Output:
sql
Question 28
Write a Python program to find out Area of Circle and Area of Triangle using function
with arguments and return value.
Code:
python
import math
# Function to calculate area of circle
def area_circle(radius):
# Inputs
# Display results
Output:
mathematica
Question 29
python
# Inputs
si = simple_interest(p, r, t)
Output:
yaml
Question 30
Code:
python
# Input sets
A = {1, 2, 3, 4, 5}
B = {4, 5, 6, 7, 8}
# Perform operations
print("Set A:", A)
print("Set B:", B)
print("Union:", A | B)
print("Intersection:", A & B)
print("Difference (A - B):", A - B)
print("Symmetric Difference:", A ^ B)
Output:
css
Set A: {1, 2, 3, 4, 5}
Set B: {4, 5, 6, 7, 8}
Union: {1, 2, 3, 4, 5, 6, 7, 8}
Intersection: {4, 5}
Shall I proceed?
You said:
yes
ChatGPT said:
Question 31
Write a Python program with using default argument function. Give a suitable
example.
Code:
python
def greet(name="Guest"):
print("Hello,", name)
# Call function
Output:
Hello, Guest
Hello, Alice
Question 32
Write a Python program with using variable length argument function. Give a
suitable example.
Code:
python
# Function with variable length arguments
def sum_numbers(*args):
total = sum(args)
print("Sum:", total)
# Call function
sum_numbers(5, 15)
Output:
makefile
Sum: 60
Sum: 20
Question 33
Write a Python program with using class and object to input two numbers by
getdata() member function to calculate sum and display in display() function.
Code:
python
class Calculator:
def getdata(self):
def display(self):
obj = Calculator()
obj.getdata()
obj.display()
Output:
mathematica
Sum = 30
Question 34
Write a Python program to illustrate the use of class and object to passing by value
to the function and calculate sum and display.
Code:
python
class Calculator:
print("Sum =", x + y)
# Create object
obj = Calculator()
obj.add(15, 25)
Output:
ini
Sum = 40
Question 35
Code:
python
# Base class
class Parent:
def show_parent(self):
# Derived class
class Child(Parent):
def show_child(self):
obj = Child()
obj.show_parent()
obj.show_child()
Output:
python
Shall I proceed?
You said:
yes
ChatGPT said:
Question 36
Code:
python
# Parent class 1
class Father:
def show_father(self):
# Parent class 2
class Mother:
def show_mother(self):
def show_child(self):
print("This is Child class")
obj = Child()
obj.show_father()
obj.show_mother()
obj.show_child()
Output:
python
Question 37
Write a Python program to illustrate the use of __init__ method. Give a suitable
example.
Code:
python
class Person:
self.name = name
self.age = age
print("Constructor called!")
def display(self):
print("Name:", self.name)
print("Age:", self.age)
# Create object
p = Person("John", 25)
p.display()
Output:
makefile
Constructor called!
Name: John
Age: 25
Question 38
Write a Python program with using try-except block. Give a suitable example.
Code:
python
try:
except ValueError:
Output:
less
Write a Python program with using try-except-else block. Give a suitable example.
Code:
python
try:
except ValueError:
print("Invalid input!")
else:
Output:
yaml
Enter a number: 50
You entered: 50
Question 40
Code:
python
try:
except ValueError:
print("Invalid input!")
else:
print("You entered:", num)
finally:
Output:
less
Invalid input!
Shall I proceed?
You said:
yes
ChatGPT said:
Question 41
Code:
python
# Square matrix
matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
# Transpose
# Display result
print("Original Matrix:")
print(row)
print("Transposed Matrix:")
print(row)
Output:
csharp
Original Matrix:
[1, 2, 3]
[4, 5, 6]
[7, 8, 9]
Transposed Matrix:
[1, 4, 7]
[2, 5, 8]
[3, 6, 9]
Question 42
Write a Python program to multiplication of two matrices.
Code:
python
# Define matrices
A=[
[1, 2, 3],
[4, 5, 6]
B=[
[7, 8],
[9, 10],
[11, 12]
# Multiply
for i in range(len(A)):
for j in range(len(B[0])):
for k in range(len(B)):
# Display result
print("Resultant Matrix:")
Output:
csharp
Resultant Matrix:
[58, 64]
[139, 154]
Question 43
Write a Python program with using file handling to create a file, write some text in
the file.
Code:
python
Output:
arduino
Question 44
Write a Python program with using file handling to open an existing file and check
“File not found” if file not available in disk.
Code:
python
try:
content = file.read()
except FileNotFoundError:
Output:
arduino
File content:
Question 45
Code:
python
content = src_file.read()
dest_file.write(content)
print("File copied successfully.")
Output:
arduino
Question 46
Write a Python program during run time to make a directory, renaming directory,
removing directory, etc.
Code:
python
import os
# Create directory
os.mkdir("test_dir")
print("Directory created.")
# Rename directory
os.rename("test_dir", "renamed_dir")
print("Directory renamed.")
# Remove directory
os.rmdir("renamed_dir")
print("Directory removed.")
Output:
Directory created.
Directory renamed.
Directory removed.