Python Lab 1
Python Lab 1
Print a message indicating that the following are the digits of the number.
Use a for loop to iterate through the digits list and print each digit.
End:
#Program
def display_digits(number):
# Ensure the input is a positive integer
if not isinstance(number, int) or number < 0:
print("Please enter a positive integer.")
return
Output:
Enter a positive integer: 5678
Digits of the number:
5
6
7
8
Get input from the user for four numbers (num1, num2, num3, num4).
Input Validation:
Use a try block and float() function to convert user input to floating-point numbers.
If the input is invalid, print an error message and exit the program.
Bubble Sort:
Output:
Enter the first number: 5
Enter the second number: 2
Enter the third number: 4
Enter the fourth number: 7
Numbers in sorted order: 2.0 4.0 5.0 7.0
Define the function calculate_mean that takes a list of numbers as input and returns the mean.
Define the function calculate_median that takes a list of numbers as input and returns the median.
Define the function calculate_mode that takes a list of numbers as input and returns the mode(s).
Define the function calculate_variance that takes a list of numbers and the mean as input, and returns
the variance.
Define the function calculate_standard_deviation that takes the variance as input and returns the
standard deviation.
Input:
Get input from the user for the number of integers (n).
Input Numbers:
Call the calculate_variance function with the list of numbers and the calculated mean.
Store the result in the variable variance.
Calculate Standard Deviation:
Print the calculated mean, median, mode, variance, and standard deviation.
End:
def calculate_mean(numbers):
return sum(numbers) / len(numbers)
def calculate_median(numbers):
sorted_numbers = sorted(numbers)
n = len(sorted_numbers)
mid = n // 2
if n % 2 == 0:
return (sorted_numbers[mid - 1] + sorted_numbers[mid]) / 2
else:
return sorted_numbers[mid]
def calculate_mode(numbers):
# Calculate the frequency of each number
frequency_dict = {}
for num in numbers:
if num in frequency_dict:
frequency_dict[num] += 1
else:
frequency_dict[num] = 1
return mode
def calculate_standard_deviation(variance):
return variance ** 0.5
Output:
Get input from the user for the number of digits (n).
Validate that n is a positive integer.
Input Number:
def is_palindrome(number):
original_number = number
reversed_number = 0
try:
num = int(input(f"Enter a {n}-digit number: "))
except ValueError:
print("Invalid input. Please enter a valid integer.")
exit()
if num < 0:
print("Please enter a non-negative integer.")
exit()
Output:
Enter the number of digits (n): 3
Enter a 3-digit number: 121
121 is a palindrome.
#5. Develop a python script to display a multiplicaion table for
given integer n.
'''Algorithm...
Start:
Validate that the input is a valid integer. If not, print an error message and exit.
Display Multiplication Table:
Print a header indicating that the following is the multiplication table for n.
Loop Through Multiplication Table:
Output:
Enter an integer to display its multiplication table: 2
Multiplication Table for 2:
2x1=2
2x2=4
2x3=6
2x4=8
2 x 5 = 10
2 x 6 = 12
2 x 7 = 14
2 x 8 = 16
2 x 9 = 18
2 x 10 = 20
#6. Develop a python script to rotate right about a given position
in that list and display them
'''Algorithm…
Start:
Define a function rotate_right that takes a list and a position as input and returns the list rotated to
the right about that position.
Input:
Call the rotate_right function with the user-input list and rotation position.
Store the result in a variable.
Display Result:
Code
return rotated_list
Output
#7. Develop a python script to interchange the digits of a given integer number.
'''Algorithm...
Start:
Define a function interchange_digits that takes an integer, digit1, and digit2 as input and returns the
number with the specified digits interchanged.
Input:
Call the interchange_digits function with the user-input number, digit1, and digit2.
Store the result in a variable.
Display Result:
return result_number
Output
Code:
def capitalize_strings(string_list):
# Use list comprehension to capitalize each string
capitalized_list = [word.capitalize() for word in string_list]
return capitalized_list
Output
Enter a list of strings separated by space: hello good
Original List: ['hello', 'good']
Capitalized List: ['Hello', 'Good']
return duplicates
Output
Enter a sentence: A woman is in love with a woman
Duplicate words and their frequencies:
a: 2
woman: 2
Get input from the user for the number of rows and columns in the array.
Input Array Elements:
Get input from the user for each element of the 2D array.
Create NumPy Array:
Code
import numpy as np
def print_row_statistics(array):
for i, row in enumerate(array):
row_sum = np.sum(row)
row_mean = np.mean(row)
row_std = np.std(row)
print(f"Row {i + 1} - Sum: {row_sum}, Mean: {row_mean}, Std Dev: {row_std}")
def print_column_statistics(array):
for j in range(array.shape[1]):
col_sum = np.sum(array[:, j])
col_mean = np.mean(array[:, j])
col_std = np.std(array[:, j])
print(f"Column {j + 1} - Sum: {col_sum}, Mean: {col_mean}, Std Dev: {col_std}")
# Get input from the user for the number of rows and columns
try:
rows = int(input("Enter the number of rows: "))
cols = int(input("Enter the number of columns: "))
except ValueError:
print("Invalid input. Please enter valid integers.")
exit()
Output
Enter the number of rows: 2
Enter the number of columns: 3
Enter element at position (1, 1): 2
Enter element at position (1, 2): 3
Enter element at position (1, 3): 4
Enter element at position (2, 1): 1
Enter element at position (2, 2): 2
Enter element at position (2, 3): 3
Row Statistics:
Row 1 - Sum: 9.0, Mean: 3.0, Std Dev: 0.816496580927726
Row 2 - Sum: 6.0, Mean: 2.0, Std Dev: 0.816496580927726
Column Statistics:
Column 1 - Sum: 3.0, Mean: 1.5, Std Dev: 0.5
Column 2 - Sum: 5.0, Mean: 2.5, Std Dev: 0.5
Column 3 - Sum: 7.0, Mean: 3.5, Std Dev: 0.5
Define a function read_and_print_csv that takes the path to a CSV file as input.
Try to open the CSV file for reading.
If the file is not found, print an error message and exit.
If any other error occurs, print the error message and exit.
Create a CSV reader using csv.reader.
Iterate through each row in the CSV file:
Print the current row.
Input:
Get input from the user for the path to the CSV file.
Read and Print CSV:
Code
import csv
def read_and_print_csv(file_path):
try:
with open(file_path, 'r') as csvfile:
# Create a CSV reader
csv_reader = csv.reader(csvfile)
# Get input from the user for the CSV file path
file_path = input("Enter the path to the CSV file: ")
Output
Enter the path to the CSV file: 3.csv
['sunny', 'Warm', 'Normal', 'Strong', 'Warm', 'Same', 'Yes']
['Sunny', 'Warm', 'High', 'Strong', 'Warm', 'Same', 'Yes']
['Rainy', 'Cold', 'High', 'Strong', 'Warm', 'Change', 'No']
['Sunny', 'Warm', 'High', 'Strong', 'Warm', 'Change', 'Yes']
Get input from the user for the path to the HTML file.
Read HTML File:
Code
def construct_html_dictionary(html_content):
html_dict = {}
return html_dict
# Get input from the user for the HTML file path
html_file_path = input("Enter the path to the HTML file: ")