Computer Programming Lab 2 - PYTHON
Computer Programming Lab 2 - PYTHON
boolean_value = False
print("Boolean:", boolean_value)
print("Type:", type(boolean_value))
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
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")
Output:
Enter the first number: 25
Enter the second number: 6
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"""
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'>
# Concatenating a String:
# Giving a space in between the first and the second-string during concatenation
new = s1 + ' ' + s2
Output:
New String = Hello World!
-----------------------------------------------------
Sub-String: Using the Slicing Operator
# Create a string
string = input("Enter a string: ")
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
Solution:
from datetime import datetime
Output:
Current Date and Time: Fri Jan 17 12:07:38 IST 2025
---------------------------------------------------------------------------------------------------------------
------------------------
5. Write a program to create, append and remove lists in Python.
Solution:
# Creating an Empty List
L = []
print(F"Initial List: {L}")
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: []
Index Element
0 85
1 20.53
2 True
3 (4+5j)
4 Python
5 [5, 10, 15, 20]
# 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)
# 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()
# 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)}")
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)
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
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:
---------------------------------------------------------------------------------------------------------------
------------------------