Practical No.4.
- Numbers and Functions in Python II
1) Write a program that asks the user to enter an angle between −180◦ and 180◦. Using an expression with
the modulo operator, convert the angle to its equivalent between 0◦ and 360◦.
Code:-
angle = float(input("Enter an angle between -180 and 180: "))
converted_angle = angle % 360
print(f"The equivalent angle between 0 and 360 degrees is: {converted_angle}")
Output:-
Enter an angle between -180 and 180: -90
The equivalent angle between 0 and 360 degrees is: 270.0
2) Write the program that asks the user for a number of seconds and prints out how many minutes and
seconds that is. For instance, 200 seconds is 3 minutes and 20 seconds. [Hint: Use the // operator to get
minutes and the % operator to get seconds.]
Code:-
# Ask the user to enter the total number of seconds
total_seconds = int(input("Enter the number of seconds: "))
# Calculate minutes using integer division
minutes = total_seconds // 60
# Calculate remaining seconds using modulus
seconds = total_seconds % 60
# Display the result
print(f"{total_seconds} seconds is {minutes} minutes and {seconds} seconds.")
Output:-
Enter the number of seconds: 130
130 seconds is 2 minutes and 10 seconds.
3) Write a program that asks the user for an hour between 1 and 12 and for how many hours in the future
they want to go. Print out what the hour will be that many hours into the future.
Code:-
# Ask user to enter current hour (1 to 12)
current_hour = int(input("Enter the current hour (1 to 12): "))
# Ask user how many hours into the future
hours_ahead = int(input("How many hours into the future?: "))
# Calculate future hour using modulo
future_hour = (current_hour + hours_ahead) % 12
# Fix 0 to 12 (since 12-hour clocks don't show 0)
if future_hour == 0:
future_hour = 12
# Display result
print(f"In {hours_ahead} hours, it will be {future_hour} o'clock.")
Output:-
Enter the current hour (1 to 12): 9
How many hours into the future?: 5
In 5 hours, it will be 2 o'clock.
4) Write a program that asks the user to enter a weight in kilograms. The program should convert it to
pounds, printing the answer rounded to the nearest tenth of a pound.
Code:-
import math
# Ask the user to enter an angle in degrees
degrees = float(input("Enter an angle in degrees: "))
# Convert degrees to radians
radians = [Link](degrees)
# Calculate the sine of the angle
sine_value = [Link](radians)
# Display the result
print(f"The sine of {degrees} degrees is {sine_value}")
Output:-
Enter an angle in degrees: 90
The sine of 90.0 degrees is 1.0
5) Write a program that asks the user to enter an angle in degrees and prints out the sine of that angle.
Code:-
import math
# Ask the user to enter an angle in degrees
angle_deg = float(input("Enter an angle in degrees: "))
# Convert the angle to radians
angle_rad = [Link](angle_deg)
# Calculate the sine of the angle
sine_value = [Link](angle_rad)
# Display the result rounded to 4 decimal places
print(f"Sine of {angle_deg}° is {round(sine_value, 4)}")
Output:-
Enter an angle in degrees: 50
Sine of 50.0° is 0.766
Practical No. -5. Matrix Algebra in Python I
Consider the following matrices
A=[ 1 3 −1]
[023]
[431]
𝐵=[ 2 1 2 ]
[1 −2 5]
[130]
1) Construct above both matrices in Python and write the program.
Code:-
import numpy as np
# Define matrices A and B using numpy arrays
A = [Link]([[1, 3, -1], [0, 2, 3], [4, 3, 1]])
B = [Link]([[2, 1, 2], [1, -2, 5], [1, 3, 0]])
# Function to display a matrix with a label
def print_matrix(matrix, name):
print(f"Matrix {name}:\n{matrix}\n")
# Display matrices
print_matrix(A, "A")
print_matrix(B, "B")
Output:-
Matrix A:
[[ 1 3 -1]
[ 0 2 3]
[ 4 3 1]]
Matrix B:
[[ 2 1 2]
[ 1 -2 5]
[ 1 3 0]]
2) Find 𝐴+𝐵,𝐴−𝐵 in Python
Code:-
import numpy as np
# Define matrices A and B
A = [Link]([[1, 3, -1], [0, 2, 3], [4, 3, 1]])
B = [Link]([[2, 1, 2], [1, -2, 5], [1, 3, 0]])
# Perform matrix addition and subtraction
sum_matrix = A + B
diff_matrix = A - B
# Function to display a matrix with a label
def print_matrix(matrix, name):
print(f"{name}:\n{matrix}\n")
# Display results
print_matrix(A, "Matrix A")
print_matrix(B, "Matrix B")
print_matrix(sum_matrix, "A + B")
print_matrix(diff_matrix, "A - B")
Output:-
Matrix A:
[[ 1 3 -1]
[ 0 2 3]
[ 4 3 1]]
Matrix B:
[[ 2 1 2]
[ 1 -2 5]
[ 1 3 0]]
A + B:
[[ 3 4 1]
[ 1 0 8]
[ 5 6 1]]
A - B:
[[-1 2 -3]
[-1 4 -2]
[ 3 0 1]]
3) Find 𝐴.𝐵 in Python
Code:-
import numpy as np
# Define matrices A and B using NumPy arrays
A = [Link]([[1, 3, -1],
[0, 2, 3],
[4, 3, 1]])
B = [Link]([[2, 1, 2],
[1, -2, 5],
[1, 3, 0]])
# Multiply A and B
product = [Link](A, B)
# Function to print a matrix
def print_matrix(matrix, name):
print(f"{name}:")
for row in matrix:
print(row)
print()
# Print matrices and result
print_matrix(A, "Matrix A")
print_matrix(B, "Matrix B")
print_matrix(product, "A × B")
Output:-
Matrix A:
[1 3 -1]
[0 2 3]
[4 3 1]
Matrix B:
[2 1 2]
[1 -2 5]
[1 3 0]
A × B:
[ 4 -8 11]
[ 5 4 10]
[12 -5 23]
4) Find 𝐴−1 and 𝐵−1in Python
Code:-
import numpy as np
# Define matrices A and B
A = [Link]([[1, 3, -1], [0, 2, 3], [4, 3, 1]])
B = [Link]([[2, 1, 2], [1, -2, 5], [1, 3, 0]])
# Function to print inverse of a matrix
def print_inverse(matrix, name):
try:
inv = [Link](matrix)
print(f"Inverse of Matrix {name}:")
print([Link](inv, 3))
except [Link]:
print(f"Matrix {name} is not invertible.")
# Display results
print_inverse(A, "A")
print()
print_inverse(B, "B")
Output:-
Inverse of Matrix A:
[[-0.189 -0.162 0.297]
[ 0.324 0.135 -0.081]
[-0.216 0.243 0.054]]
Inverse of Matrix B:
[[ 1. -0.4 -0.6 ]
[-0.333 0.133 0.533]
[-0.333 0.333 0.333]]
Practical No. -6. Matrix Algebra in Python II
1) Solve 2𝑥+𝑦−𝑧=−1,𝑥−2𝑦+3𝑧=9,−𝑥+3𝑦−4𝑧=−12.
Code:-
import numpy as np
# Coefficient matrix A
A = [Link]([[2, 1, -1],
[1, -2, 3],
[-1, 3, -4]])
# Constants matrix D (RHS)
D = [Link]([-1, 9, -12])
# Calculate determinant of A
det_A = [Link](A)
# Check if solution exists
if det_A == 0:
print("The system has no unique solution.")
else:
# Replace columns and calculate determinants
A_x = [Link]()
A_x[:, 0] = D
det_x = [Link](A_x)
A_y = [Link]()
A_y[:, 1] = D
det_y = [Link](A_y)
A_z = [Link]()
A_z[:, 2] = D
det_z = [Link](A_z)
# Apply Cramer's Rule
x = round(det_x / det_A, 3)
y = round(det_y / det_A, 3)
z = round(det_z / det_A, 3)
# Output the result
print("Solution:")
print("x =", x)
print("y =", y)
print("z =", z)
Output:-
Solution:
x = 1.0
y = -1.0
z = 2.0
2) Solve 𝑥+𝑦+𝑧=6,2𝑥+𝑦+3𝑧=13,5𝑥+2𝑦+𝑧=12,2𝑥−3𝑦−2𝑧=−10
Code:-
import numpy as np
# Coefficient matrix (4 equations, 3 variables)
A = [Link]([
[1, 1, 1],
[2, 1, 3],
[5, 2, 1],
[2, -3, -2]
])
# Right-hand side values
B = [Link]([6, 13, 12, -10])
# Solve using least squares
solution, residuals, rank, s = [Link](A, B, rcond=None)
# Print solution
x, y, z = [Link](solution, 3)
print("x =", x)
print("y =", y)
print("z =", z)
Output:-
x = 1.0
y = 2.0
z = 3.0
3) Find Eigen Values and Eigen Vectors - [ 4 −1]
[21]
Code:-
import numpy as np
# Define the matrix A
A = [Link]([[4, -1],
[2, 1]])
# Compute eigenvalues and eigenvectors
eigenvalues, eigenvectors = [Link](A)
# Display results (rounded for readability)
print("Eigenvalues:")
for val in eigenvalues:
print(round(val, 3))
print("\nEigenvectors (columns):")
for vec in eigenvectors.T:
print([Link](vec, 3))
Output:-
Eigenvalues:
3.0
2.0
Eigenvectors (columns):
[0.707 0.707]
[0.447 0.894]
4) Find Eigen Values an d Eigen Vectors - [−2 7]
[23]
Code:-
import numpy as np
# Define the matrix A
A = [Link]([[-2, 7],
[ 2, 3]])
# Compute eigenvalues and eigenvectors
eigenvalues, eigenvectors = [Link](A)
# Print eigenvalues
print("Eigenvalues:")
for val in eigenvalues:
print(round(val, 3))
# Print eigenvectors
print("\nEigenvectors (columns):")
# Round for clean output
print([Link](eigenvectors, 3))
Output:-
Eigenvalues:
-4.0
5.0
Eigenvectors (columns):
[[-0.962 -0.707]
[ 0.275 -0.707]]
5) Find Eigen Values and Eigen Vectors -[ 4 0 1 ]
[−2 1 0 ]
[ −2 0 1]
Code:-
import numpy as np
# Coefficients of the polynomial x³ - 6x² + 5x
coefficients = [1, -6, 5, 0]
# Find roots using numpy
roots = [Link](coefficients)
# Print the roots
print("Roots (Eigenvalues) are:")
for i, val in enumerate(roots, 1):
print(f"Root {i} = {round(val, 3)}")
Output:-
Roots (Eigenvalues) are:
Root 1 = 5.0
Root 2 = 1.0
Root 3 = 0.0
Practical No. – 7 . Calculus with python I
1) Use Python to solve lim( 𝑥 − 1).
𝑥→1
Code:
def f(x):
return x - 1
# Values approaching 1 from left and right
x_values = [0.9, 0.99, 0.999, 1.0, 1.001, 1.01, 1.1]
print("x\t\tf(x) = x - 1")
print("-----------------------------")
for x in x_values:
print(f"{x:.3f}\t\t{f(x):.6f}")
Output :
x f(x) = x - 1
-----------------------------
0.900 -0.100000
0.990 -0.010000
0.999 -0.001000
1.000 0.000000
1.001 0.001000
1.010 0.010000
1.100 0.100000
2) Use Python to solve lim 𝑥
𝑥→3 (𝑥+3)
Code:
def f(x):
return x / (x + 3)
# Values approaching 3 from both sides
x_values = [2.9, 2.99, 2.999, 3.0, 3.001, 3.01, 3.1]
print("x\t\tf(x) = x / (x + 3)")
print("-------------------------------")
for x in x_values:
print(f"{x:.3f}\t\t{f(x):.6f}")
Output :
x f(x) = x / (x + 3)
-------------------------------
2.900 0.491525
2.990 0.499165
2.999 0.499917
3.000 0.500000
3.001 0.500083
3.010 0.500832
3.100 0.508197
3) Use Python to solve .
Code:
def f(x):
return (x**2 - 4) / (x + 2)
x_values = [-0.1, -0.01, -0.001, 0.0, 0.001, 0.01, 0.1]
print("x\t\tf(x) = (x^2 - 4)/(x + 2)")
print("---------------------------------------")
for x in x_values:
print(f"{x:.3f}\t\t{f(x):.6f}")
Output:
x f(x) = (x^2 - 4)/(x + 2)
---------------------------------------
-0.100 -2.100000
-0.010 -2.010000
-0.001 -2.001000
0.000 -2.000000
0.001 -1.999000
0.010 -1.990000
0.100 -1.900000
4) Find 𝑑𝑦 if 𝑦 = 3𝑥2 + 2𝑥 + 4 by Python.
𝑑𝑥
Code:
def f(x):
return 3 * x**2 + 2 * x + 4
def derivative(f, x, h=1e-5):
return (f(x + h) - f(x)) / h
# Test at x = 1
x_val = 1
print("Approximate derivative at x =", x_val, "is", derivative(f, x_val))
Output:
Approximate derivative at x = 1 is 8.000030000054892
5) Find 𝑑𝑢 if 𝑢 = 7𝑡3 + 3𝑡 − 2 by Python.
𝑑𝑡
Code:
def u(t):
return 7 * t**3 + 3 * t - 2
def derivative(u, t, h=1e-5):
return (u(t + h) - u(t)) / h
# Example: Approximate derivative at t = 1
t_val = 1
print("Approximate du/dt at t =", t_val, "is", derivative(u, t_val))
Output:
Approximate du/dt at t = 1 is 24.000210000885144
Practical No. – 8 . Calculus with python II.
1) Find 𝜕𝑦 if 𝑦 = 𝑥2𝑧𝑡 using Python.
𝜕𝑥
Code:
def y(x, z, t):
return x**2 * z * t
def partial_derivative_x(x, z, t, h=1e-5):
return (y(x + h, z, t) - y(x, z, t)) / h
# Example: estimate at x=1, z=2, t=3
print("Approximate ∂y/∂x at (1,2,3):", partial_derivative_x(1, 2, 3))
Output:
Approximate ∂y/∂x at (1,2,3): 12.000060000083577
2) Find 𝜕𝑦 if 𝑦 = 3𝑥3𝑡 + 𝑡2 + 2𝑥𝑡 using Python.
𝜕𝑥
Code:
def y(x, t):
return 3 * x**3 * t + t**2 + 2 * x * t
def partial_derivative_x(x, t, h=1e-5):
return (y(x + h, t) - y(x, t)) / h
# Example: Estimate at x = 1, t = 2
print("Approximate ∂y/∂x at (1,2):", partial_derivative_x(1, 2))
Output:
Approximate ∂y/∂x at (1,2): 22.00018000078074
3) Solve by using Python ∫ 𝑥2 𝑑𝑥.
Code:
def f(x):
return x**2
def integrate_trapezoid(a, b, n=1000):
h = (b - a) / n
total = 0.5 * (f(a) + f(b))
for i in range(1, n):
total += f(a + i * h)
return total * h
# Example: ∫ x^2 dx from x=0 to x=3
a=0
b=3
result = integrate_trapezoid(a, b)
print(f"Approximate ∫ x^2 dx from {a} to {b} is:", result)
Output:
Approximate ∫ x^2 dx from 0 to 3 is: 9.000004500000005
4) Solve by using Python ∫(𝑥3 − 2𝑥 + 1)𝑑𝑥.
Code:
def f(x):
return x**3 - 2*x + 1
def integrate_trapezoid(a, b, n=1000):
h = (b - a) / n
total = 0.5 * (f(a) + f(b))
for i in range(1, n):
total += f(a + i * h)
return total * h
# Example: ∫ from x = 0 to x = 2
a=0
b=2
result = integrate_trapezoid(a, b)
print(f"Approximate ∫(x³ − 2x + 1) dx from {a} to {b} is:", result)
Output:
Approximate ∫(x³ − 2x + 1) dx from 0 to 2 is: 2.000003999999999
5) Solve by using Python 𝑘𝑥 𝑑𝑥.
Code:
def f(x, k):
return k * x
def integrate_trapezoid(a, b, k, n=1000):
h = (b - a) / n
total = 0.5 * (f(a, k) + f(b, k))
for i in range(1, n):
total += f(a + i * h, k)
return total * h
# Example: k = 3
k_val = 3
a=0
b=2
result = integrate_trapezoid(a, b, k_val)
print(f"Approximate ∫₀² {k_val}x dx =", result)
Output:
Approximate ∫₀² 3x dx = 6.000000000000001