Python Practical’s
Practical No : 1
A. Write a program that asks the user to enter their name and their age. Print out a message
addressed to them that tells them the year that they will turn 100 years old
from datetime import datetime
def main():
name = input("Enter your name: ")
while True:
try:
age = int(input("Enter your age: "))
break
except ValueError:
print("Please enter a valid number for your age.")
current_year = datetime.now().year
year_turn_100 = current_year + (100 - age)
print(f"Hello {name}, you will turn 100 years old in the year {year_turn_100}.")
if __name__ == "__main__":
main()
Output:
Enter your name: Amruta
Enter your age: 27
Hello Amruta, you will turn 100 years old in the year 2098.
B. Write a program to accept a number from the user and depending on whether the number is even
or odd, print out an appropriate message to the user
def main():
try:
number = int(input("Enter a number: "))
if number % 2 == 0:
print(f"The number {number} is even.")
else:
print(f"The number {number} is odd.")
except ValueError:
print("That is not a valid number. Please enter an integer.")
if __name__ == "__main__":
main()
Output:
Enter a number: 2
The number 2 is even.
c. Write a program to accept the SGPI from the user and print corresponding grade based on the
following: d. SGPI Grade e. 9.00 – 10.00 O f. 8.00 – 8.99 A+ g. 7.00 – 7.99 A h. 6.00 – 6.99 B+ i. 5.50
– 5.99 B j. 5.00 – 5.49 C k. 4.00 – 4.99 P l. Below 4 F
def main():
try:
sgpi = float(input("Enter your SGPI (0.00 to 10.00): "))
if sgpi < 0 or sgpi > 10:
print("Invalid SGPI. Please enter a value between 0.00 and 10.00.")
return
if 9.00 <= sgpi <= 10.00:
grade = "O"
elif 8.00 <= sgpi < 9.00:
grade = "A+"
elif 7.00 <= sgpi < 8.00:
grade = "A"
elif 6.00 <= sgpi < 7.00:
grade = "B+"
elif 5.50 <= sgpi < 6.00:
grade = "B"
elif 5.00 <= sgpi < 5.50:
grade = "C"
elif 4.00 <= sgpi < 5.00:
grade = "P"
else:
grade = "F"
print(f"Your grade is: {grade}")
except ValueError:
print("Invalid input. Please enter a numeric value.")
if __name__ == "__main__":
main()
Output:
Enter your SGPI (0.00 to 10.00): 4.00
Your grade is: P
Practical No: 2- Write programs for the following:
a. Write a program to generate the Fibonacci series.
def main():
try:
n = int(input("Enter the number of terms for the Fibonacci series: "))
if n <= 0:
print("Please enter a positive integer.")
return
a, b = 0, 1
print("Fibonacci Series:")
for i in range(n):
print(a, end=" ")
a, b = b, a + b # Next term
except ValueError:
print("Invalid input. Please enter a whole number.")
if __name__ == "__main__":
main()
b. Write a program to accept a number from the user display sum of its digits.
def main():
try:
num = int(input("Enter a number: "))
num = abs(num)
digit_sum = 0
while num > 0:
digit_sum += num % 10
num = num // 10
print(f"The sum of the digits is: {digit_sum}")
except ValueError:
print("Invalid input. Please enter a valid integer.")
if __name__ == "__main__":
main()
Output:
Enter a number: 10
The sum of the digits is: 1
Practical No: 3- Write programs for the following:
a. Write a program to perform basic operations, indexing and
slicing on arrays.
import array
def main():
arr = array.array('i', [10, 20, 30, 40, 50, 60, 70])
print("Original Array:", arr)
arr.append(80) # Append an element
arr.insert(2, 25) # Insert 25 at index 2
arr.remove(40) # Remove element 40
arr.pop() # Remove the last element
print("After Basic Operations:", arr)
print("Element at index 0:", arr[0])
print("Element at last index:", arr[-1])
print("Slice from index 1 to 4:", arr[1:5])
print("Slice from beginning to index 3:", arr[:4])
print("Slice from index 3 to end:", arr[3:])
print("Reversed Array:", arr[::-1])
if __name__ == "__main__":
main()
Output:
Original Array: array('i', [10, 20, 30, 40, 50, 60, 70])
After Basic Operations: array('i', [10, 20, 25, 30, 50, 60, 70])
Element at index 0: 10
Element at last index: 70
Slice from index 1 to 4: array('i', [20, 25, 30, 50])
Slice from beginning to index 3: array('i', [10, 20, 25, 30])
Slice from index 3 to end: array('i', [30, 50, 60, 70])
Reversed Array: array('i', [70, 60, 50, 30, 25, 20, 10])
b. Write a program to implement mathematical functions on
arrays.
import numpy as np
def main():
arr = np.array([1, 4, 9, 16, 25, 36])
print("Original Array:", arr)
sqrt_arr = np.sqrt(arr) # Square root
square_arr = np.square(arr) # Square
log_arr = np.log(arr) # Natural logarithm
exp_arr = np.exp(arr) # Exponential
sin_arr = np.sin(arr) # Sine of each element
sum_arr = np.sum(arr) # Sum of all elements
mean_arr = np.mean(arr) # Mean value
max_val = np.max(arr) # Maximum value
min_val = np.min(arr) # Minimum value
print("Square Roots:", sqrt_arr)
print("Squares:", square_arr)
print("Logarithms:", log_arr)
print("Exponentials:", exp_arr)
print("Sine Values:", sin_arr)
print("Sum:", sum_arr)
print("Mean:", mean_arr)
print("Maximum Value:", max_val)
print("Minimum Value:", min_val)
if __name__ == "__main__":
main()
Output:
Original Array: [ 1 4 9 16 25 36]
Square Roots: [1. 2. 3. 4. 5. 6.]
Squares: [ 1 16 81 256 625 1296]
Logarithms: [0. 1.38629436 2.19722458 2.77258872 3.21887582 3.58351894]
Exponentials: [2.71828183e+00 5.45981500e+01 8.10308393e+03 8.88611052e+06
7.20048993e+10 4.31123155e+15]
Sine Values: [ 0.84147098 -0.7568025 0.41211849 -0.28790332 -0.13235175 -0.99177885]
Sum: 91
Mean: 15.166666666666666
Maximum Value: 36
Minimum Value: 1
c. Write a program to perform array aliasing and copying.
import numpy as np
def main():
print("=== List Aliasing and Copying ===")
list1 = [10, 20, 30]
list_alias = list1 # Aliasing
list_copy = list1.copy() # Copying
list1[0] = 100
print("Original list:", list1)
print("Aliased list:", list_alias) # Reflects changes
print("Copied list:", list_copy) # Does not reflect changes
print("\n=== NumPy Array Aliasing and Copying ===")
arr1 = np.array([1, 2, 3, 4])
arr_alias = arr1 # Aliasing
arr_copy = arr1.copy() # Deep copy
arr1[1] = 200
print("Original NumPy array:", arr1)
print("Aliased NumPy array:", arr_alias) # Reflects changes
print("Copied NumPy array:", arr_copy) # Unchanged
if __name__ == "__main__":
main()
Output:
Original NumPy array: [ 1 200 3 4]
Aliased NumPy array: [ 1 200 3 4]
Copied NumPy array: [1 2 3 4]
4. Write programs for the following:
a. Write a program to perform slicing, basic and advanced indexing on
import numpy as np
# Create a 2D NumPy array
array = np.array([
[11, 22, 33, 44],
[55, 66, 77, 88],
[99, 100, 111, 122]
])
print("Original Array:\n", array)
# ---------------------------
# 1. SLICING
# ---------------------------
print("\nSLICING:")
# Slice first two rows and first three columns
slice_1 = array[:2, :3]
print("First 2 rows, first 3 columns:\n", slice_1)
# Slice every element in the second column
slice_2 = array[:, 1]
print("Second column:", slice_2)
# Slice last two rows
slice_3 = array[1:, :]
print("Last two rows:\n", slice_3)
# ---------------------------
# 2. BASIC INDEXING
# ---------------------------
print("\nBASIC INDEXING:")
# Access element at row 1, column 2
elem_1 = array[1, 2]
print("Element at (1, 2):", elem_1)
# Access the last element
elem_2 = array[-1, -1]
print("Last element:", elem_2)
# ---------------------------
# 3. ADVANCED INDEXING
# ---------------------------
print("\nADVANCED INDEXING:")
# Using arrays of indices
row_indices = np.array([0, 2])
col_indices = np.array([1, 3])
advanced_1 = array[row_indices, col_indices]
print("Elements at (0,1) and (2,3):", advanced_1)
# Boolean indexing
greater_than_60 = array[array > 60]
print("Elements greater than 60:\n", greater_than_60)
b. NumPy arrays.
c. Write a program to analyze dimensions and attributes of arrays
5. Write programs for the following:
a. Write a function to check the input value is Armstrong and also write the function for
Palindrome.
b. Write a recursive function to print the factorial for a given number.
c. Write a lambda function that checks whether a given string starts with a specific
character.
6. Write programs for the following:
a. Write a program to compute number of characters and words in a string
b. Create a file geometry.py to calculate base areas for shapes square and circle. In
another file, write a function pointyShapeVolume(x, y, squareBase) that calculates the
volume of a square pyramid if squareBase is True and of a right circular cone if squareBase
is Faise. x is the length of an edge on a square if squareBase is True and the radius of a
circle when squareBase is False, y is the height of the object. First use squareBase to
distinguish, the cases, Use the circleArea and square Area from the geometry module to
calculate the base areas.