0% found this document useful (0 votes)
2 views15 pages

Computer Programming Lab 2 - PYTHON

The document outlines a Computer Programming Lab course with various Python programming exercises. It includes solutions for demonstrating number data types, performing arithmetic operations, creating and manipulating strings, printing the current date, and working with lists and tuples. Each section provides code examples and expected outputs for clarity.

Uploaded by

howtoaddme
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
0% found this document useful (0 votes)
2 views15 pages

Computer Programming Lab 2 - PYTHON

The document outlines a Computer Programming Lab course with various Python programming exercises. It includes solutions for demonstrating number data types, performing arithmetic operations, creating and manipulating strings, printing the current date, and working with lists and tuples. Each section provides code examples and expected outputs for clarity.

Uploaded by

howtoaddme
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1/ 15

Computer Programming Lab – II

Course Code: 23C01302

Programs for Practice


1. Write a program to demonstrate different number data types in Python

Solution: Demonstrating different number data types in Python


# Integer data type
integer_number = 42
print("Integer:", integer_number)
print("Type:", type(integer_number))
print()

# Float data type


float_number = 42.42
print("Float:", float_number)
print("Type:", type(float_number))
print()

# Complex data type


complex_number = 4 + 2j
print("Complex:", complex_number)
print("Type:", type(complex_number))
print()

# Binary data type - Integer


# Binary representation of 42
binary_number = 0b101010
print("Binary (0b101010) =", binary_number)
print("Type:", type(binary_number))
print()

# Octal data type - Integer


# Octal representation of 42
octal_number = 0o52
print("Octal (0o52) =", octal_number)
print("Type:", type(octal_number))
print()

# Hexadecimal data type - Integer


# Hexadecimal representation of 42
hexadecimal_number = 0x2A
print("Hexadecimal (0x2A) =", hexadecimal_number)
print("Type:", type(hexadecimal_number))
print()

# Boolean data type


boolean_value = True
print("Boolean:", boolean_value)
print("Type:", type(boolean_value))

boolean_value = False
print("Boolean:", boolean_value)
print("Type:", type(boolean_value))
print()

# Number representation of Boolean values: True=1 and False=0


print("True + True =" , (True+True))
print("True - False =" , (True-False))
print()

Output:
Integer: 42
Type: <class 'int'>

Float: 42.42
Type: <class 'float'>

Complex: (4+2j)
Type: <class 'complex'>

Binary (0b101010) = 42
Type: <class 'int'>

Octal (0o52) = 42
Type: <class 'int'>

Hexadecimal (0x2A) = 42
Type: <class 'int'>

Boolean: True
Type: <class 'bool'>
Boolean: False
Type: <class 'bool'>

True + True = 2
True - False = 1
---------------------------------------------------------------------------------------------------------------
-------------------------
2. Write a program to perform different Arithmetic Operations on numbers in
Python

Solution: Program to perform different Arithmetic Operations on numbers

# Getting input from the user


num1 = float(input("Enter the first number: "))
num2 = float(input("Enter the second number: "))

# Performing arithmetic operations


addition = num1 + num2
subtraction = num1 - num2
multiplication = num1 * num2
division = num1 / num2
modulus = num1 % num2
floor_division = num1 // num2
exponentiation = num1 ** num2

# Displaying the results


print("\nArithmetic Operations Results:")
print(F"{num1} + {num2} = {addition}")
print(F"{num1} - {num2} = {subtraction}")
print(F"{num1} * {num2} = {multiplication}")
print(F"{num1} / {num2} = {division}")
print(F"{num1} % {num2} = {modulus}")
print(F"{num1} ** {num2} = {exponentiation}")
print(F"{num1} // {num2} = {floor_division}")

print()

# When we try to divide a number by Zero, we get an ZeroDivisionError and the program
terminates displaying this and does not execute the rest of the code.
# To avoid this error - we can rewrite the program as:

print("Division By Zero")

# Getting input from the user


num1 = float(input("Enter the first number: "))
num2 = float(input("Enter the second number: "))

# Rewriting the code to accommodate Division By Zero


division = num1 / num2 if num2 != 0 else "Division by zero not possible"
modulus = num1 % num2 if num2 != 0 else "Division by zero not possible"
floor_division = num1 // num2 if num2 != 0 else "Division by zero not possible"

# Printing the Result


print(F"{num1} / {num2} = {division}")
print(F"{num1} % {num2} = {modulus}")
print(F"{num1} // {num2} = {floor_division}")

Output:
Enter the first number: 25
Enter the second number: 6

Arithmetic Operations Results:


25.0 + 6.0 = 31.0
25.0 - 6.0 = 19.0
25.0 * 6.0 = 150.0
25.0 / 6.0 = 4.166666666666667
25.0 % 6.0 = 1.0
25.0 ** 6.0 = 244140625.0
25.0 // 6.0 = 4.0

Division By Zero
Enter the first number: 85
Enter the second number: 0
85.0 / 0.0 = Division by zero not possible
85.0 % 0.0 = Division by zero not possible
85.0 // 0.0 = Division by zero not possible
---------------------------------------------------------------------------------------------------------------
------------------------
3. Write a program to create, concatenate and print a string and accessing sub-
string from a given string.

String Creation:
# Creating a String - Direct Initialization
s1 = 'Welcome to Python'
s2 = "Welcome to Python"
s3 = '''Welcome to Python'''
s4 = """Welcome to Python"""

# Printing the String


print(F"{s1} --> Type = {type(s1)}")
print(F"{s2} --> Type = {type(s2)}")
print(F"{s3} --> Type = {type(s3)}")
print(F"{s4} --> Type = {type(s4)}")
print()

# Creating a String - Dynamic Input


s5 = input("Enter the String: ")
print(F"{s5} --> Type = {type(s5)}")
print()

# Creating a String - Dynamic Input


s6 = eval(input("Enter the String: "))
print(F"{s6} --> Type = {type(s6)}")
print()

Output:
Welcome to Python --> Type = <class 'str'>
Welcome to Python --> Type = <class 'str'>
Welcome to Python --> Type = <class 'str'>
Welcome to Python --> Type = <class 'str'>

Enter the String: Good Morning!


Good Morning! --> Type = <class 'str'>

Enter the String: 'Happy Birthday :)'


Happy Birthday :) --> Type = <class 'str'>
-----------------------------------------------------
String Concatenation: '+' Operator is used for this purpose
# Creating String
s1 = 'Hello'
s2 = 'World!'

# Concatenating a String:
# Giving a space in between the first and the second-string during concatenation
new = s1 + ' ' + s2

# Printing the new string


print(F"New String = {new}")

Output:
New String = Hello World!
-----------------------------------------------------
Sub-String: Using the Slicing Operator
# Create a string
string = input("Enter a string: ")

# Take start and end indices as input


start_index = int(input("Enter the start index for substring extraction: "))
end_index = int(input("Enter the end index for substring extraction: "))

# Extract substring using slicing


substring = string[start_index:end_index]

# Display the result


print("Extracted Substring:", substring)

Output:
Enter a string: Welcome to Python Programming Language
Enter the start index for substring extraction: 10
Enter the end index for substring extraction: 17
Extracted Substring: Python
-----------------------------------------------------
Solution: Program to create, concatenate, and print strings and access substrings
# Creating strings
string1 = input("Enter the first string: ")
string2 = input("Enter the second string: ")
print()

# Concatenating strings
new = string1 + ' ' + string2
print("Concatenated String:", new)
print()

# Accessing substring
start_index = int(input("Enter the start index for substring extraction: "))
end_index = int(input("Enter the end index for substring extraction: "))
substring = new[start_index:end_index]
print("Extracted Substring:", substring)

Output:
Enter the first string: Welcome to
Enter the second string: Python Programming

Concatenated String: Welcome to Python Programming

Enter the start index for substring extraction: 10


Enter the end index for substring extraction: 17
Extracted Substring: Python
---------------------------------------------------------------------------------------------------------------
------------------------
4. Write a Python script to print the current date in the following format: "Sun
May 29 02:26:23 IST 2025"

Solution:
from datetime import datetime

# Get the current date and time


current_time = datetime.now()

# Format the date and time


formatted_date = current_time.strftime("%a %b %d %H:%M:%S IST %Y")

# Print the formatted date


print("Current Date and Time:", formatted_date)

Output:
Current Date and Time: Fri Jan 17 12:07:38 IST 2025

 The strftime() function: "string format time."


 It is used to format date and time objects into readable string.
 It is a method of the datetime class
Common Format Codes:
Cod Meaning Example Output
e
%a Abbreviated weekday name Sun
%A Full weekday name Sunday
%w Weekday as a number (0=Sunday) 0
%d Day of the month (01-31) 29
%b Abbreviated month name May
%B Full month name May
%m Month as a number (01-12) 05
%y Year without century (00-99) 25
%Y Year with century 2025
%H Hour (00-23) 14
%I Hour (01-12) 02
%p AM/PM PM
%M Minute (00-59) 26
%S Second (00-59) 23
%f Microsecond (000000-999999) 123456
%z UTC offset in the form +HHMM/-HHMM +0530
%Z Timezone name IST
%j Day of the year (001-366) 149
%U Week number of the year (Sunday as the first day of 21
the week)
%W Week number of the year (Monday as the first day 21
of the week)
%c Locale’s date and time Sun May 29 14:26:23
2025
%x Locale’s date 05/29/25
%X Locale’s time 14:26:23

---------------------------------------------------------------------------------------------------------------
------------------------
5. Write a program to create, append and remove lists in Python.

 Creating a List  Direct Initialization (or) Dynamic Input


 append()  pre-defined list function that is used to add elements to the end of the
list
 remove()  pre-defined function that will remove the element from the list based on
the value. And if the value is repeated multiple times, it removes the first occurrence
of the element from the list. If the specified element is not present – it will generate
an Error
 pop()  pre-defined function that will remove the element from the list based on the
index position. If the specified index position is not valid – it will generate an Error
 clear()  pre-defined function that will remove the entire content of the list, making
it empty.

Solution:
# Creating an Empty List
L = []
print(F"Initial List: {L}")
print()

# Appending elements to the list


n = int(input("How many elements would you like to add to the list? : "))
for i in range(n):
element = eval(input("Enter an element to add: "))
L.append(element)
print()

# Printing the List after adding the values


print("Index Value")
for i,v in enumerate(L):
print(F"{i}\t{v}")
print()

while True:
# Removing elements from the list - based on Value (or) Index
print("Remove Element from the List based on:\n1.Value\n2.Index\n3.Exit")
option = int(input("Enter your choice: "))
# Based on Element
if option == 1:
ele = eval(input("Enter the Element to be removed: "))
# If the element is found - remove otherwise print 'not found message'
if ele in L:
L.remove(ele)
print(F"{ele}: has been deleted successfully")
print()
else:
print(F"{ele}: is not found within the List")
print()
# Based on Index
elif option == 2:
ind = int(input("Enter the Index position to delete: "))
# If the index position is valid - remove the element otherwise print 'invalid index
position'
if ind < len(L):
x = L.pop(ind)
print(F"Index {ind} with value --> {x} has been successfully deleted")
print()
else:
print("Invalid Index Position entered")
print()
# Ending the loop
elif option == 3:
break
# Any other input given other than 1/2/3
else:
print("Invalid Option Entered")
print()

Output:
Initial List: []

How many elements would you like to add to the list? : 6


Enter an element to add: 85
Enter an element to add: 20.53
Enter an element to add: True
Enter an element to add: 4+5j
Enter an element to add: 'Python'
Enter an element to add: [5,10,15,20]

Index Element
0 85
1 20.53
2 True
3 (4+5j)
4 Python
5 [5, 10, 15, 20]

Remove Element from the List based on:


1.Value
2.Index
3.Exit
Enter your choice: 1
Enter the Element to be removed: True
True: has been deleted successfully

Remove Element from the List based on:


1.Value
2.Index
3.Exit
Enter your choice: 1
Enter the Element to be removed: 'Java'
Java: is not found within the List

Remove Element from the List based on:


1.Value
2.Index
3.Exit
Enter your choice: 2
Enter the Index position to delete: 1
Index 1 with value --> 20.53 has been successfully deleted

Remove Element from the List based on:


1.Value
2.Index
3.Exit
Enter your choice: 10
Invalid Option Entered

Remove Element from the List based on:


1.Value
2.Index
3.Exit
Enter your choice: 3
---------------------------------------------------------------------------------------------------------------
------------------------
6. Write a program to demonstrate working with tuples in Python

Solution: Program to demonstrate working with tuples in Python

# Creating tuples
t1 = ()
t2 = (5,) # Comma is necessary for a single-element tuple
t3 = (1, 2, 3, 4, 5)
t4 = (1, "Hello", 3.14, True)

# Printing the Tuple values


print("Empty Tuple:", t1)
print("Single Element Tuple:", t2)
print("Multiple Elements Tuple:", t3)
print("Mixed Type Tuple:", t4)
print()

# Accessing elements in a tuple


print("Accessing Elements:")
print(F"Tuple: {t4}")
print("First Element:", t4[0])
print("Last Element:", t4[-1])
print("Slice (2nd to 4th element):", t4[1:4])
print()

# Iterating through a tuple


print("Iterating through the tuple:")
print("Index Value")
for i,v in enumerate(t4):
print(F"{i}\t{v}")
print()

# Tuple Concatenation
print("Tuple Concatenation:")
new_tuple = t4 + (6, 7, 8)
print("Concatenated Tuple:", new_tuple)
print()

# Tuple Repetition
print("Tuple Repetition:")
print(F"Original Tuple: {t2}")
repeated_tuple = t2 * 3
print("Repeated Tuple:", repeated_tuple)
print()

# Tuple unpacking
print("Tuple Unpacking:")
print("Tuple:" , t3)
a, b, c, d, e = t3
print("Unpacked Values:", a, b, c, d, e)
print()

# Membership Testing
print("Using the Membership Operators to Search")
print("Tuple:" , t3)
print(F"3 present in the Tuple: {3 in t3}")
print(F"6 not present in the Tuple: {6 not in t3}")
print()

# Length of Tuple
print("Finding the Length of the Tuple")
print("Tuple:" , t3)
print(F"Length = {len(t3)}")
print()

# Counting Occurrences
print("Counting the Occurrences of an element within the Tuple")
t5 = (1, 2, 2, 3, 4, 2)
print(F"2 Occurs {t5.count(2)} times within the tuple")
print()

# Finding Index
print("Finding the Index position of an element")
t6 = (10, 20, 30, 40, 50)
print("Tuple:" , t6)
print(F"The Index Position of the value 30 is: {t6.index(30)}")
print()

# Sum, Min, Max


t7 = (10, 20, 30, 40)
print("Tuple:" , t7)
print(F"Sum: {sum(t7)}")
print(F"Maximum Value: {max(t7)}")
print(F"Minimum Value: {min(t7)}")
print()

# Tuple Conversion
print("Converting an Object into a Tuple")
L1 = [10,20,30,40,50]
print(F"List: {L1}")
print(F"Converted to Tuple: {tuple(L1)}")

S1 = "Java"
print(F"String: {S1}")
print(F"Converted to Tuple: {tuple(S1)}")

S2 = {'C', 'C++', 'Java'}


print(F"Set: {S2}")
print(F"Converted to Tuple: {tuple(S2)}")
print()

# Using tuples to return multiple values from a function


def calculate(a, b):
return a + b, a * b, a - b

result = calculate(5, 3)
print("Tuple as Function Return Value")
print("Addition, Multiplication, Subtraction:", result)

Output:
Empty Tuple: ()
Single Element Tuple: (5,)
Multiple Elements Tuple: (1, 2, 3, 4, 5)
Mixed Type Tuple: (1, 'Hello', 3.14, True)

Accessing Elements:
Tuple: (1, 'Hello', 3.14, True)
First Element: 1
Last Element: True
Slice (2nd to 4th element): ('Hello', 3.14, True)

Iterating through the tuple:


Index Value
0 1
1 Hello
2 3.14
3 True

Tuple Concatenation:
Concatenated Tuple: (1, 'Hello', 3.14, True, 6, 7, 8)

Tuple Repetition:
Original Tuple: (5,)
Repeated Tuple: (5, 5, 5)

Tuple Unpacking:
Tuple: (1, 2, 3, 4, 5)
Unpacked Values: 1 2 3 4 5

Using the Membership Operators to Search


Tuple: (1, 2, 3, 4, 5)
3 present in the Tuple: True
6 not present in the Tuple: True

Finding the Length of the Tuple


Tuple: (1, 2, 3, 4, 5)
Length = 5

Counting the Occurrences of an element within the Tuple


2 Occurs 3 times within the tuple

Finding the Index position of an element


Tuple: (10, 20, 30, 40, 50)
The Index Position of the value 30 is: 2

Tuple: (10, 20, 30, 40)


Sum: 100
Maximum Value: 40
Minimum Value: 10

Converting an Object into a Tuple


List: [10, 20, 30, 40, 50]
Converted to Tuple: (10, 20, 30, 40, 50)
String: Java
Converted to Tuple: ('J', 'a', 'v', 'a')
Set: {'C', 'C++', 'Java'}
Converted to Tuple: ('C', 'C++', 'Java')

Tuple as Function Return Value


Addition, Multiplication, Subtraction: (8, 15, 2)
---------------------------------------------------------------------------------------------------------------
------------------------
7. Write a program to demonstrate working with dictionaries in Python

Solution:

Output:

---------------------------------------------------------------------------------------------------------------
------------------------
8. Write a Python program to find the largest of three numbers.

Solution:

Output:

---------------------------------------------------------------------------------------------------------------
------------------------
9. Write a Python program to convert temperatures to and from Celsius,
Fahrenheit.

Solution:
Output:

---------------------------------------------------------------------------------------------------------------
------------------------
10. Write a Python program to construct the following pattern, using a nested for
loop.
*
**
***
****
*****
****
***
**
*

Solution:

---------------------------------------------------------------------------------------------------------------
------------------------
11. Write a Python script to print the Prime Numbers less than 20.

Solution:

Output:

---------------------------------------------------------------------------------------------------------------
------------------------
12. Write a Python program to find the Factorial of a given number using
Recusion.

Solution:

Output:

---------------------------------------------------------------------------------------------------------------
------------------------
13. Write a Python program that accepts the length of three sides of a Triangle
as input. The program output should indicate whether or not the triangle is a
Right triangle (Recall from the Pythagorean Theorem that in a Right Triangle, the
square of one side equals the sum of the squares of the other two sides).

Solution:

Output:

---------------------------------------------------------------------------------------------------------------
------------------------
14. Write a Python program to define a Module to find Fibonacci Numbers and
import the Module to another program.
Solution:

Output:

---------------------------------------------------------------------------------------------------------------
------------------------
15. Write a Python program to define a Module and import a specific function int
that module to another program.

Solution:

Output:

---------------------------------------------------------------------------------------------------------------
------------------------
16. Write a Python script named copyfile.py. This script should prompt the user
for the names of two text files. The content of the first file should be input and
written to the second file.

Solution:

Output:

---------------------------------------------------------------------------------------------------------------
------------------------
17. Write a program that inputs a text file. The program should print all the
unique words in the file in alphabetical order.

Solution:

Output:

---------------------------------------------------------------------------------------------------------------
------------------------
18. Write a Python class to convert an integer to a roman numeral.

Solution:

Output:

---------------------------------------------------------------------------------------------------------------
------------------------
19. Write a Python class to implement pow(x,n).

Solution:

Output:

---------------------------------------------------------------------------------------------------------------
------------------------
20. Write a Python class to reverse a string word by word.
Solution:

Output:

---------------------------------------------------------------------------------------------------------------
------------------------

You might also like