PYTHON PROGRAMMING LAB
1. Install and run the Python interpreter.
Aim: To install Python and run the Python interpreter on a computer.
Requirements
Computer or Laptop
Internet connection
Web browser
Python installer from Python official site [Link]
Procedure
Step 1: Download Python
Open a web browser.
Go to the official website: [Link]
Click Downloads.
Download the latest version of Python for your operating
system (Windows / Linux / macOS).
Step 2: Install Python
Open the downloaded Python installer file.
Check the option “Add Python to PATH”.
Click Install Now.
Wait until the installation process is completed.
Step 3: Run the Python Interpreter
Open Command Prompt (Windows) or Terminal.
Type the following command:
Python
Press Enter.
Step 4: Python Interpreter Starts
You will see the Python prompt like this:
Python 3.x.x (default, ...)
Type "help", "copyright", "credits" or "license" for
more information.
>>>
The symbol >>> indicates that the Python interpreter is
ready to accept commands.
Step 5: Test Python
Type a simple command:
>>> print("Hello, Python")
OUTPUT:
Hello, Python
2. Start a Python Interpreter and Use it as a Calculator
Aim: To start the Python interpreter and perform basic arithmetic operations
using it as a calculator.
Procedure
Step 1: Open Python Interpreter
Open Command Prompt (Windows) or Terminal.
Type the command:
python
3. Press Enter.
The Python interpreter starts and displays the prompt:
>>>
Step 2: Use Python as a Calculator
At the >>> prompt, type arithmetic expressions.
Addition:
>>> 5 + 3
Output:
8
Subtraction
>>> 10 - 4
Output:
6
Multiplication
>>> 6 * 7
Output:
42
Division
>>> 20 / 5
Output:
4.0
Modulus (Remainder)
>>> 17 % 3
Output:
2
Power
>>> 2 ** 3
Output:
8
Step 3: Exit Python Interpreter
Type:
exit()
or press Ctrl + Z and then Enter (Windows).
3. Write a program to calculate compound interest when principal, rate
and number of periods is given.
# Program to calculate Compound Interest
P = float(input("Enter the principal amount: "))
R = float(input("Enter the rate of interest: "))
N = int(input("Enter the number of periods: "))
# Calculate amount
A = P * (1 + R/100) ** N
# Calculate compound interest
CI = A - P
print("Total Amount =", A)
print("Compound Interest =", CI)
OUTPUT:
Enter the principal amount: 10000
Enter the rate of interest: 6
Enter the number of periods: 3
Total Amount = 11910.16
Compound Interest = 1910.1599999999999
4. Read name, address, email and phone number of a person through
keyboard and print the details.
Aim: Read personal details from the keyboard
name = input("Enter your name: ")
address = input("Enter your address: ")
email = input("Enter your email: ")
phone = input("Enter your phone number: ")
# Print the details
print("\nPerson Details")
print("Name:", name)
print("Address:", address)
print("Email:", email)
print("Phone Number:", phone)
OUTPUT:
Enter your name: Radha
Enter your address: Kakinada
Enter your email: h@[Link]
Enter your phone number: 7894561230
Person Details
Name: Radha
Address: Kakinada
Email: h@[Link]
Phone Number: 7894561230
5. Print the below triangle using for loop. 5
4 4
3 3 3
2 2 2 2
1 1 1 1 1
AIM: Program to print the triangle pattern
for i in range(5, 0, -1): # outer loop for rows
for j in range(6 - i): # inner loop for printing numbers
print(i, end=" ")
print()
OUTPUT:
5
44
333
2222
11111
6. Write a program to check weather the given input is digit or lowercase
character or uppercase character or a special character (use if else if
ladder) .
Aim: Program to check the type of input character# Program to check
the type of input character
ch = input("Enter a character: ")
if [Link]():
print("It is a digit.")
elif [Link]():
print("It is a lowercase character.")
elif [Link]():
print("It is an uppercase character.")
else:
print("It is a special character.")
OUTPUT:
Enter a character: 0
It is a digit.
Enter a character: #
It is a special character.
7. Python program to print all prime numbers in a given interval (use
break)
Aim: Program to print prime numbers in a given interval
Program:
start = int(input("Enter starting number: "))
end = int(input("Enter ending number: "))
print("Prime numbers in the given interval are:")
for num in range(start, end + 1):
if num > 1:
for i in range(2, num):
if num % i == 0:
break # Not a prime number
else:
print(num)
OUTPUT:
Enter starting number: 10
Enter ending number: 20
Prime numbers in the given interval are:
11
13
17
19
8. Write a program to convert a list and tuple into arrays.
Aim:Program to convert list and tuple into arrays
Program:
import array
# List
list_data = [1, 2, 3, 4, 5]
# Tuple
tuple_data = (6, 7, 8, 9, 10)
# Convert list to array
array_from_list = [Link]('i', list_data)
# Convert tuple to array
array_from_tuple = [Link]('i', tuple_data)
# Display results
print("Array from list:", array_from_list)
print("Array from tuple:", array_from_tuple)
OUTPUT:
Array from list: array('i', [1, 2, 3, 4, 5])
Array from tuple: array('i', [6, 7, 8, 9, 10])
9. Write a program to find common values between two arrays.
Aim: Program to find common values between two arrays
Program:
import array
# Define two arrays
arr1 = [Link]('i', [1, 2, 3, 4, 5])
arr2 = [Link]('i', [3, 4, 5, 6, 7])
# Find common elements
common = []
for i in arr1:
if i in arr2:
[Link](i)
# Display result
print("Common elements are:", common)
OUTPUT:
Common elements are: [3, 4, 5]
[Link] a function called palindrome that takes a string argument and
returns True if it is a palindrome and False otherwise. Remember that
you can use the built-in function len to check the length of a string.
Aim: Python function to check whether a given string is a palindrome:
def palindrome(s):
# Remove spaces and convert to lowercase (optional, for better
checking)
s = [Link](" ", "").lower()
# Check if the string is equal to its reverse
if s == s[::-1]:
return True
else:
return False
# Example usage
text = input("Enter a string: ")
if palindrome(text):
print("It is a palindrome")
else:
print("It is not a palindrome")
OUTPUT:
Enter a string: madam
It is a palindrome
[Link] a function called is_sorted that takes a list as a parameter and
returns True if the list is sorted in ascending order and False otherwise.
Aim: Python function to check whether a list is sorted in ascending order.
Program:
def is_sorted(lst):
# Compare each element with the next one
for i in range(len(lst) - 1):
if lst[i] > lst[i + 1]:
return False
return True
# Example usage
numbers = list(map(int, input("Enter elements separated by space:
").split()))
if is_sorted(numbers):
print("The list is sorted in ascending order")
else:
print("The list is not sorted")
OUTPUT:
Enter elements separated by space: 1 2 3 4 5
The list is sorted in ascending order
[Link] a function called has_duplicates that takes a list and returns true
if there is any element that appears more than once. It should not
modify the original list.
Aim: Python function to check if a list contains duplicate elements.
Program:
def has_duplicates(lst):
seen = set() # empty set to store elements
for item in lst:
if item in seen:
return True # duplicate found
[Link](item)
return False # no duplicates found
# Example usage
numbers = list(map(int, input("Enter elements separated by space:
").split()))
if has_duplicates(numbers):
print("List has duplicates")
else:
print("List has no duplicates")
Output:
Enter elements separated by space: 1 2 3 4
List has no duplicates
[Link] a function called remove_duplicates that takes a list and returns
a new list with only the unique elements from the original. Hint: they
don’t have to be in the same order.
Aim: Python function to remove duplicates from a list:
Program:
def remove_duplicates(lst):
unique_list = []
for item in lst:
if item not in unique_list:
unique_list.append(item)
return unique_list
# Calling the function
numbers = [1, 2, 2, 3, 4, 4, 5]
result = remove_duplicates(numbers)
print(result)
OUTPUT:
[1, 2, 3, 4, 5]
[Link] wordlist I provided, [Link], doesn’t contain single letter words.
So you might want to add “I”, “a”, and the empty string.
Program:
def load_words():
try:
with open("[Link]", "r") as file:
words = [Link]().split()
# Add missing words
words += ["I", "a", ""]
return words
except FileNotFoundError:
print("Error: [Link] file not found!")
return []
# Calling the function
word_list = load_words()
# Display output
print(word_list)
OUTPUT:
[Link] a python code to read dictionary values from the user. Construct
a function to invert its content. i.e., keys should be values and values
should be keys.
Aim: [Link] dictionary values from the user
[Link] the dictionary (swap keys and values)
Program:
def invert_dict(original_dict):
inverted_dict = {}
for key in original_dict:
value = original_dict[key]
inverted_dict[value] = key # swap key and value
return inverted_dict
# Taking input from user
n = int(input("Enter number of key-value pairs: "))
my_dict = {}
for i in range(n):
key = input("Enter key: ")
value = input("Enter value: ")
my_dict[key] = value
# Display original dictionary
print("Original Dictionary:", my_dict)
# Invert dictionary
result = invert_dict(my_dict)
# Display inverted dictionary
print("Inverted Dictionary:", result)
OUTPUT:
Enter number of key-value pairs: 4
Enter key: m
Enter value: 3
Enter key: n
Enter value: 4
Enter key: o
Enter value: 5
Enter key: p
Enter value: 6
Original Dictionary: {'m': '3', 'n': '4', 'o': '5', 'p': '6'}
Inverted Dictionary: {'3': 'm', '4': 'n', '5': 'o', '6': 'p'}
[Link] a comma between the characters. If the given word is 'Apple', it
should become 'A,p,p,l,e'.
Program:
def add_commas(word):
result = ",".join(word)
return result
# Taking input
word = input("Enter a word: ")
# Calling function
output = add_commas(word)
# Display result
print("Output:", output)
OUTPUT:
Enter a word: Apple
Output: A,p,p,l,e
[Link] the given word in all the places in a string?
Program:
def remove_word(sentence, word):
words = [Link]()
result = []
for w in words:
if w != word:
[Link](w)
return " ".join(result)
sentence = input("Enter a sentence: ")
word = input("Enter word to remove: ")
print("Output:", remove_word(sentence, word))
OUTPUT:
Enter a sentence: The Sun Shines Brightly today
Enter word to remove: today
Output: The Sun Shines Brightly
[Link] a function that takes a sentence as an input parameter and
replaces the first letter of every word with the corresponding upper
case letter and the rest of the letters in the word by corresponding
letters in lower case without using a built-in function?
def format_sentence(sentence):
result = ""
new_word = True # To track start of a new word
for ch in sentence:
if ch == " ":
result += ch
new_word = True # Next character starts a new word
else:
if new_word:
# Convert to uppercase manually
if 'a' <= ch <= 'z':
result += chr(ord(ch) - 32)
else:
result += ch
new_word = False
else:
# Convert to lowercase manually
if 'A' <= ch <= 'Z':
result += chr(ord(ch) + 32)
else:
result += ch
return result
# Input from user
sentence = input("Enter a sentence: ")
# Output
print("Output:", format_sentence(sentence))
OUTPUT:
Enter a sentence: HeLLo PYTHON ProgrAMMING
Output: Hello Python Programming
[Link] a recursive function that generates all binary strings of n-bit
length.
Program:
def generate_binary(n, current=""):
if n == 0:
print(current)
return
# Add '0' and recurse
generate_binary(n - 1, current + "0")
# Add '1' and recurse
generate_binary(n - 1, current + "1")
# Input from user
n = int(input("Enter number of bits: "))
# Function call
generate_binary(n)
OUTPUT:
Enter number of bits: 3
000
001
010
011
100
101
110
111
[Link] a python program that defines a matrix and prints
Program:
# Define a matrix (2D list)
matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
# Print the matrix
for row in matrix:
print(row)
OUTPUT:
[1, 2, 3]
[4, 5, 6]
[7, 8, 9]
[Link] a python program to perform addition of two square matrices
Aim: program to add two square matrices step by step.
Program:
def add_matrices(A, B, n):
result = []
for i in range(n):
row = []
for j in range(n):
[Link](A[i][j] + B[i][j]) # Add corresponding elements
[Link](row)
return result
# Input: size of matrix
n = int(input("Enter the size of square matrix (n x n): "))
print("Enter elements of Matrix A:")
A = []
for i in range(n):
row = list(map(int, input().split()))
[Link](row)
print("Enter elements of Matrix B:")
B = []
for i in range(n):
row = list(map(int, input().split()))
[Link](row)
# Function call
result = add_matrices(A, B, n)
# Display result
print("Resultant Matrix after Addition:")
for row in result:
print(row)
OUTPUT:
Enter the size of square matrix (n x n): 2
Enter elements of Matrix A:
12
34
Enter elements of Matrix B:
56
78
Resultant Matrix after Addition:
[6, 8]
[10, 12]
[Link] a python program to perform multiplication of two square
matrices.
Aim: Python program to multiply two square matrices.
Program:
def multiply_matrices(A, B, n):
result = []
for i in range(n):
row = []
for j in range(n):
sum = 0
for k in range(n):
sum += A[i][k] * B[k][j] # Multiply and add
[Link](sum)
[Link](row)
return result
# Input: size of matrix
n = int(input("Enter the size of square matrix (n x n): "))
print("Enter elements of Matrix A:")
A = []
for i in range(n):
row = list(map(int, input().split()))
[Link](row)
print("Enter elements of Matrix B:")
B = []
for i in range(n):
row = list(map(int, input().split()))
[Link](row)
# Function call
result = multiply_matrices(A, B, n)
# Display result
print("Resultant Matrix after Multiplication:")
for row in result:
print(row)
OUTPUT:
Enter the size of square matrix (n x n): 3
Enter elements of Matrix A:
345
135
246
Enter elements of Matrix B:
567
7 9 11
8 12 14
Resultant Matrix after Multiplication:
[83, 114, 135]
[66, 93, 110]
[86, 120, 142]