0% found this document useful (0 votes)
5 views3 pages

Python Programs for Math Operations

Uploaded by

rrrroptv
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views3 pages

Python Programs for Math Operations

Uploaded by

rrrroptv
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

53. Create a module to check whether a number is a prime or not.

Write a program to find


the prime number between two limits using this module.
Ans: The module: [Link]
def is_prime(number):
if number < 2:
return False
for i in range(2, int(number**0.5) + 1):
if number % i == 0:
return False
return True
The program:
from PrimeCheckerModule import is_prime

def find_primes_in_range(start, end):


prime_numbers = []
for num in range(start, end + 1):
if is_prime(num):
prime_numbers.append(num)
return prime_numbers

if __name__ == "__main__":
start_limit = int(input("Enter the start limit: "))
end_limit = int(input("Enter the end limit: "))
primes_in_range = find_primes_in_range(start_limit, end_limit)
if primes_in_range:
print(f"Prime numbers between {start_limit} and {end_limit}:")
print(primes_in_range)
else:
print(f"No prime numbers found between {start_limit} and {end_limit}.")

54. Create a module to find the factorial of a number and import the module from the main
program to find the factorial of a given number.
Ans: The module: [Link]
def factorial(n):
if n == 0 or n == 1:
return 1
else:
return n * factorial(n - 1)
The program:
from FactorialModule import factorial
if __name__ == "__main__":
num = int(input("Enter a number to find its factorial: "))
result = factorial(num)
print(f"The factorial of {num} is: {result}")
55. Write a program to find the mean, median, and standard deviation of a list of random
numbers between 1 and 10.
Ans: Required program:
import random
import statistics

def generate_random_numbers(n):
return [[Link](1, 10) for _ in range(n)]

if __name__ == "__main__":
random_numbers = generate_random_numbers(10)
mean_value = [Link](random_numbers)
median_value = [Link](random_numbers)
std_deviation = [Link](random_numbers)
print("Generated random numbers:", random_numbers)
print("Mean:", mean_value)
print("Median:", median_value)
print("Standard Deviation:", std_deviation)

56. Write a program to shuffle elements of a list of random numbers between given
ranges.
Ans:
import random
def generate_random_numbers(n, lower_limit, upper_limit):
return [[Link](lower_limit, upper_limit) for _ in range(n)]
if __name__ == "__main__":
n = int(input("Enter the number of elements: "))
lower_limit = int(input("Enter the lower limit: "))
upper_limit = int(input("Enter the upper limit: "))
random_numbers = generate_random_numbers(n, lower_limit, upper_limit)
print("Original list:", random_numbers)
[Link](random_numbers)
print("Shuffled list:", random_numbers)

57. Write a program to create a list of random numbers using list comprehension.
Ans:
import random
def generate_random_numbers(n, lower_limit, upper_limit):
return [[Link](lower_limit, upper_limit) for _ in range(n)]
if __name__ == "__main__":
n = int(input("Enter the number of elements: "))
lower_limit = int(input("Enter the lower limit: "))
upper_limit = int(input("Enter the upper limit: "))
random_numbers = generate_random_numbers(n, lower_limit, upper_limit)
print("Generated list of random numbers:", random_numbers)

__________________________________________________________________________________
Exception Handling
58. Write a program to read a number from the user. If the number is positive or zero,
print it, otherwise raise an exception.
Ans:
try:
number = float(input("Enter a number: "))
if number >= 0:
print("Entered number:", number)
else:
raise ValueError("Entered number is negative.")

except ValueError as e:
print(f"Error: {e}")

59. Write a program to read two numbers from the user and perform basic mathematical
operations (addition, multiplication, subtraction, division) by handling all possible
exceptions.
Ans:
def add(x, y):
return x + y

def subtract(x, y):


return x - y

def multiply(x, y):


return x * y

def divide(x, y):


if y == 0:
raise ValueError("Cannot divide by zero.")
return x / y
try:
num1 = float(input("Enter the first number: "))
num2 = float(input("Enter the second number: "))
result_addition = add(num1, num2)
result_subtraction = subtract(num1, num2)
result_multiplication = multiply(num1, num2)
result_division = divide(num1, num2)
print(f"Addition: {result_addition}")
print(f"Subtraction: {result_subtraction}")
print(f"Multiplication: {result_multiplication}")
print(f"Division: {result_division}")
except ValueError as ve:
print(f"Error: {ve}")
except Exception as e:
print(f"An unexpected error occurred: {e}")

Common questions

Powered by AI

Handling user input errors ensures robustness in programs by preventing runtime exceptions and ensuring the program can handle unexpected input gracefully. In the number-checking program, if a user enters a negative number when a non-negative one is expected, the program raises a ValueError, which is caught and handled with an error message. This maintains program stability and provides feedback to the user .

List comprehension enhances the program for generating random numbers by allowing a concise and readable expression to create lists. It integrates the iteration and the function call needed to generate random numbers into a single line of code, reducing boilerplate and making the intention of the code clearer .

The algorithm used to determine if a number is prime involves checking divisibility from 2 up to the square root of the number. This reduces unnecessary checks, as any non-prime number n must have at least one factor less than or equal to √n. The time complexity of this algorithm is O(√n).

The method used to calculate factorial recursively involves defining a function that calls itself with decremented arguments until a base case is reached. Specifically, if the input number n is 0 or 1, the function returns 1. Otherwise, it returns n multiplied by the factorial of (n-1). This forms a chain of function calls that eventually compute the factorial .

Shuffling a list of numbers primarily affects the ordering of data without changing its statistical properties like mean, median, or standard deviation. However, it can significantly impact any statistical analysis that depends on order, such as certain forms of time-series analysis. In cases where the order holds specific importance, shuffling may invalidate certain assumptions of the analysis .

The approach involves raising a ValueError when an attempt to divide by zero occurs, which is then caught in a try-except block. This strategy is effective because it prevents the program from crashing, allows for meaningful error messages to be displayed, and enables the handling of exceptions separately from the main logic, making the code more robust and maintainable .

Using recursion to solve factorials can be limited by the amount of stack memory available, as each recursive call consumes stack space. For large inputs, this can lead to a stack overflow error if the system's maximum recursion depth is exceeded. It also involves repeated function call overhead, which can incur additional computational expense versus iterative approaches. Thus, for large numbers, iterative methods are generally preferred for efficiency and reliability .

Limiting the range of division checks to numbers up to the square root of the target number reduces the total number of operations needed to determine primality. This method harnesses the mathematical property that any non-prime number n must have a factor less than or equal to √n, effectively reducing the time complexity from O(n) to O(√n). This optimization is particularly significant in enhancing performance for large numbers .

The statistical measures calculated from a list of random numbers include mean, median, and standard deviation. The mean provides the average value, the median gives the middle value when sorted, and the standard deviation indicates the spread or dispersion of the numbers around the mean. These measures help summarize and understand the distribution and variability within the dataset .

Using modules like 'primechecker.py' and 'FactorialModule.py' offers several benefits including code reusability, organization, and easier maintenance. Modules allow separate functionalities to be encapsulated and reused across multiple programs, reducing redundancy. They also make the codebase more organized, enabling easier updates and debugging in modular segments rather than in one monolithic code block .

You might also like