0% found this document useful (0 votes)
21 views

M1 -Pgm3838

The document contains a series of Python programming exercises that cover various topics such as pattern generation, user input handling, mathematical calculations, and basic algorithms. Each exercise includes a description of the task, followed by sample code that demonstrates how to implement the solution. The exercises range from simple tasks like checking for palindromes to more complex ones like calculating the roots of quadratic equations and generating Fibonacci series.

Uploaded by

cirab29938
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)
21 views

M1 -Pgm3838

The document contains a series of Python programming exercises that cover various topics such as pattern generation, user input handling, mathematical calculations, and basic algorithms. Each exercise includes a description of the task, followed by sample code that demonstrates how to implement the solution. The exercises range from simple tasks like checking for palindromes to more complex ones like calculating the roots of quadratic equations and generating Fibonacci series.

Uploaded by

cirab29938
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
You are on page 1/ 12

‭ .Write a Python program to construct the following pattern using nested for loop.

(7‬
1
‭Marks)‬

*‭ ‬
‭* *‬
‭* * *‬
‭* * * *‬
‭* * * * *‬
‭* * * *‬
‭* * *‬
‭* *‬
‭*‬

‭n = 5‬

‭ Upper half of the pattern (including middle row)‬


#
‭for i in range(1, n+1):‬
‭for j in range(1, i+1):‬
‭print("*", end=" ")‬
‭print() # Move to the next line‬

‭ Lower half of the pattern (after middle row)‬


#
‭for i in range(n-1, 0, -1):‬
‭for j in range(1, i+1):‬
‭print("*", end=" ")‬
‭print() # Move to the next line‬

‭ . Write a Python program that takes a series of numbers from the user and calculates‬
2
‭their sum and average.‬

‭ = int(input("Enter the number of elements: "))‬


n
‭total_sum = 0‬

‭ Read each number and calculate the sum‬


#
‭for i in range(n):‬
‭# Taking user input for each number‬
‭num = float(input(f"Enter number {i + 1}: "))‬

‭ Add the number to the total sum‬


#
‭total_sum += num‬

‭ Calculate the average‬


#
‭average = total_sum / n‬
‭ Display the sum and average‬
#
‭print(f"Sum of the numbers: {total_sum}")‬
‭print(f"Average of the numbers: {average}")‬

‭ . Write a Python program to generate the following type of pattern for the given N rows.‬
3
‭(7 Marks)‬
‭1‬
‭1 2‬
‭1 2 3‬
‭1 2 3 4‬

‭# Program to generate the pattern for the given N rows‬

‭ Get the number of rows from the user‬


#
‭N = int(input("Enter the number of rows: "))‬

‭ Generate the pattern‬


#
‭for i in range(1, N+1):‬
‭# Print numbers from 1 to i‬
‭for j in range(1, i+1):‬
‭print(j, end=" ")‬
‭print() # Move to the next line after each row‬

‭ . Write a Python code to determine whether the given string is a Palindrome or not using‬
4
‭slicing. Do not use any string function.‬

‭# Program to check if the string is a palindrome using slicing‬

‭ Input the string‬


#
‭string = input("Enter a string: ")‬

‭ Check if the string is equal to its reverse using slicing‬


#
‭if string == string[::-1]:‬
‭print("The string is a palindrome.")‬
‭else:‬
‭print("The string is not a palindrome.")‬

‭ .Write a Python program to reverse a number and also find the sum of digits of the‬
5
‭number.‬
‭# Prompt user for input‬
‭number = int(input("Enter a number: "))‬

‭ Initialize variables‬
#
‭reverse = 0‬
‭digit_sum = 0‬

‭ Store the original number for later use in reversing‬


#
‭original_number = number‬

‭ Reverse the number and calculate the sum of digits‬


#
‭while number > 0:‬
‭digit = number % 10 # Extract the last digit‬
‭reverse = reverse * 10 + digit # Add the digit to the reverse number‬
‭digit_sum += digit # Add the digit to the sum of digits‬
‭number = number // 10 # Remove the last digit from the number‬

‭ Output the reversed number and the sum of digits‬


#
‭print(f"The reversed number is: {reverse}")‬
‭print(f"The sum of digits is: {digit_sum}")‬

‭6. Write a Python program to check whether the given number is an Armstrong or not.‬

‭ Prompt user for input‬


#
‭number = int(input("Enter a number: "))‬

‭ Convert the number to a string to easily find the number of digits‬


#
‭num_str = str(number)‬
‭num_digits = len(num_str)‬

‭ Initialize the sum variable to 0‬


#
‭sum_of_powers = 0‬

‭ Calculate the sum of digits raised to the power of the number of digits‬
#
‭for digit in num_str:‬
‭sum_of_powers += int(digit) ** num_digits‬

‭ Check if the sum of the powers is equal to the original number‬


#
‭if sum_of_powers == number:‬
‭print(f"{number} is an Armstrong number.")‬
‭else:‬
‭print(f"{number} is not an Armstrong number.")‬

‭# Another method to check Armstrong number‬


‭ Input the number‬
#
‭number = int(input("Enter a number: "))‬

‭ Find the number of digits in the number‬


#
‭num_digits = len(str(number))‬

‭ Initialize a variable to store the sum of digits raised to the power of num_digits‬
#
‭sum_of_powers = 0‬

‭ Store the original number to check at the end‬


#
‭original_number = number‬

‭ Calculate the sum of digits raised to the power of num_digits‬


#
‭while number > 0:‬
‭digit = number % 10 # Extract the last digit‬
‭sum_of_powers += digit ** num_digits # Raise the digit to the power of num_digits and‬
‭add to sum‬
‭number //= 10 # Remove the last digit from the number‬

‭ Check if the sum of powers is equal to the original number‬


#
‭if sum_of_powers == original_number:‬
‭print(f"{original_number} is an Armstrong number.")‬
‭else:‬
‭print(f"{original_number} is not an Armstrong number.")‬

‭ .Write a Python program to check whether a given number is Fibonacci or not.‬


5
‭import math‬

‭ Prompt the user for input‬


#
‭number = int(input("Enter a number: "))‬

‭ Check if 5 * n^2 + 4 or 5 * n^2 - 4 is a perfect square‬


#
‭x1 = 5 * number * number + 4‬
‭x2 = 5 * number * number - 4‬

‭ Check if either x1 or x2 is a perfect square‬


#
‭sqrt_x1 = int(math.sqrt(x1))‬
‭sqrt_x2 = int(math.sqrt(x2))‬

‭ If the square of sqrt_x1 or sqrt_x2 equals the original x1 or x2, the number is Fibonacci‬
#
‭if sqrt_x1 * sqrt_x1 == x1 or sqrt_x2 * sqrt_x2 == x2:‬
‭print(f"{number} is a Fibonacci number.")‬
‭else:‬
‭print(f"{number} is not a Fibonacci number.")‬

‭7.Write a Python code to check whether a given year is a leap year or not.‬

‭ Prompt user for input‬


#
‭year = int(input("Enter a year: "))‬

‭ Check if the year is a leap year‬


#
‭if (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0):‬
‭print(f"{year} is a leap year.")‬
‭else:‬
‭print(f"{year} is not a leap year.")‬

‭8. Write a Python program to find the roots of a quadratic equation.‬

‭import cmath # Importing cmath to handle complex square roots‬

‭ Prompt user for the coefficients of the quadratic equation‬


#
‭a = float(input("Enter the coefficient a: "))‬
‭b = float(input("Enter the coefficient b: "))‬
‭c = float(input("Enter the coefficient c: "))‬

‭ Calculate the discriminant (b^2 - 4ac)‬


#
‭discriminant = b**2 - 4*a*c‬

‭ Calculate the two roots using the quadratic formula‬


#
‭root1 = (-b + cmath.sqrt(discriminant)) / (2 * a)‬
‭root2 = (-b - cmath.sqrt(discriminant)) / (2 * a)‬

‭ Print the roots‬


#
‭print(f"The roots of the quadratic equation are {root1} and {root2}")‬

‭9.Write a Python program to find LCM of two given numbers.‬

‭ Prompt user for input‬


#
‭num1 = int(input("Enter the first number: "))‬
‭num2 = int(input("Enter the second number: "))‬

‭ Store the original values of num1 and num2‬


#
‭a = num1‬
‭b = num2‬

‭# Find the GCD of num1 and num2 using the Euclidean algorithm‬
‭while b != 0:‬
‭a, b = b, a % b‬

‭ Now, calculate the LCM using the formula LCM(a, b) = abs(a * b) // GCD(a, b)‬
#
‭lcm = abs(num1 * num2) // a‬

‭ Display the result‬


#
‭print(f"The LCM of {num1} and {num2} is {lcm}.")‬

‭10. Write a Python program to find the gcd of a given number.‬

‭ Prompt user for input‬


#
‭num1 = int(input("Enter the first number: "))‬
‭num2 = int(input("Enter the second number: "))‬

‭ Store the original values of num1 and num2‬


#
‭a = num1‬
‭b = num2‬

‭ Use the Euclidean algorithm to find the GCD‬


#
‭while b != 0:‬
‭a, b = b, a % b‬

‭ Display the result‬


#
‭print(f"The GCD of {num1} and {num2} is {a}.")‬

‭11. Design a simple calculator using Python conditional statements.‬

‭ Display menu to user‬


#
‭print("Select operation:")‬
‭print("1. Add")‬
‭print("2. Subtract")‬
‭print("3. Multiply")‬
‭print("4. Divide")‬

‭ Prompt user for input‬


#
‭choice = input("Enter choice (1/2/3/4): ")‬

‭ Check if the input choice is valid‬


#
‭if choice in ['1', '2', '3', '4']:‬
‭# Prompt user for two numbers‬
‭num1 = float(input("Enter the first number: "))‬
‭num2 = float(input("Enter the second number: "))‬
‭ Perform the operation based on user choice‬
#
‭if choice == '1':‬
‭result = num1 + num2‬
‭print(f"The result of {num1} + {num2} is: {result}")‬
‭elif choice == '2':‬
‭result = num1 - num2‬
‭print(f"The result of {num1} - {num2} is: {result}")‬
‭elif choice == '3':‬
‭result = num1 * num2‬
‭print(f"The result of {num1} * {num2} is: {result}")‬
‭elif choice == '4':‬
‭if num2 != 0:‬
‭result = num1 / num2‬
‭print(f"The result of {num1} / {num2} is: {result}")‬
‭else:‬
‭print("Error! Division by zero is not allowed.")‬
‭else:‬
‭print("Invalid input! Please select a valid operation (1/2/3/4).")‬

‭ 2. Write a Python program to find X^Y or pow(X,Y) without using standard functions.‬
1
‭# Program to find X^Y without using standard functions‬

‭ Prompt user for input‬


#
‭X = float(input("Enter the base (X): "))‬
‭Y = int(input("Enter the exponent (Y): "))‬

‭ Initialize result to 1 (since any number to the power of 0 is 1)‬


#
‭result = 1‬

‭ If Y is positive, use a loop to multiply X, Y times‬


#
‭if Y > 0:‬
‭for i in range(Y):‬
‭result *= X‬

‭ If Y is negative, calculate the reciprocal of X raised to the positive Y‬


#
‭elif Y < 0:‬
‭for i in range(abs(Y)):‬
‭result *= X‬
‭result = 1 / result‬

‭ If Y is 0, the result is 1 (X^0 is 1 for any X)‬


#
‭else:‬
‭result = 1‬

‭ Display the result‬


#
‭print(f"{X} raised to the power {Y} is: {result}")‬

‭ 3.Write a Python program to enter a number from 1 to 7 and display the corresponding‬
1
‭day of the week using statements.‬

‭ Get user input‬


#
‭day_number = int(input("Enter a number between 1 and 7: "))‬

‭ Display the corresponding day of the week using if-elif-else statements‬


#
‭if day_number == 1:‬
‭print("Monday")‬
‭elif day_number == 2:‬
‭print("Tuesday")‬
‭elif day_number == 3:‬
‭print("Wednesday")‬
‭elif day_number == 4:‬
‭print("Thursday")‬
‭elif day_number == 5:‬
‭print("Friday")‬
‭elif day_number == 6:‬
‭print("Saturday")‬
‭elif day_number == 7:‬
‭print("Sunday")‬
‭else:‬
‭print("Invalid input! Please enter a number between 1 and 7.")‬

‭15. Write a Python program to print Fibonacci series up to a given limit.‬

‭ Prompt user for the limit‬


#
‭limit = int(input("Enter the limit up to which you want to print the Fibonacci series: "))‬

‭ Initialize the first two Fibonacci numbers‬


#
‭a, b = 0, 1‬

‭ Print Fibonacci series until the number exceeds the limit‬


#
‭print("Fibonacci series up to", limit, ":")‬
‭while a <= limit:‬
‭print(a, end=" ")‬
‭a, b = b, a + b # Update a and b to the next numbers in the series‬

‭ 6. Write a Python program to count numbers between 1 to 100 not divisible by 2, 3 and‬
1
‭5.‬

‭ Initialize counter‬
#
‭count = 0‬

‭ Iterate through numbers from 1 to 100‬


#
‭for num in range(1, 101):‬
‭# Check if the number is not divisible by 2, 3, or 5‬
‭if num % 2 != 0 and num % 3 != 0 and num % 5 != 0:‬
‭count += 1‬

‭ Output the result‬


#
‭print(f"Count of numbers between 1 and 100 not divisible by 2, 3 or 5: {count}")‬

‭16.Write a Python program to find the sum of cubes of n natural numbers.‬

‭ Prompt user to input the value of n‬


#
‭n = int(input("Enter a number n to find the sum of cubes of first n natural numbers: "))‬

‭ Initialize the sum‬


#
‭sum_of_cubes = 0‬

‭ Loop to calculate the sum of cubes‬


#
‭for i in range(1, n + 1):‬
‭sum_of_cubes += i ** 3‬

‭ Display the result‬


#
‭print(f"The sum of the cubes of the first {n} natural numbers is: {sum_of_cubes}")‬

‭ 6. Write a Python program to print all numbers between 100 and 1000 whose sum of the‬
1
‭digits are divisible by 9.‬

‭ Loop through numbers from 100 to 999‬


#
‭for num in range(100, 1000):‬
‭# Calculate the sum of digits of the number‬
‭sum_of_digits = sum(int(digit) for digit in str(num))‬

‭ Check if the sum of digits is divisible by 9‬


#
‭if sum_of_digits % 9 == 0:‬
‭print(num)‬
‭17. Write a Python program to generate prime numbers within a certain range.‬

‭ Get input from the user for the range‬


#
‭start = int(input("Enter the start of the range: "))‬
‭end = int(input("Enter the end of the range: "))‬

‭ Loop through the range and check for prime numbers‬


#
‭print(f"Prime numbers between {start} and {end} are:")‬
‭for num in range(start, end + 1):‬
‭if num <= 1:‬
‭continue # Skip numbers less than or equal to 1‬
‭is_prime = True # Assume the number is prime‬
‭for i in range(2, int(num ** 0.5) + 1):‬
‭if num % i == 0: # If divisible by any number, it's not prime‬
‭is_prime = False‬
‭break‬
‭if is_prime:‬
‭print(num, end=" ")‬
‭18. Write a loop that outputs the numbers in a list named salaries. The output should be‬
‭formatted in a column that is right justified, with a field width of 12 and a precision of 2.‬

‭ List of salaries‬
#
‭salaries = [2500.45, 3200.50, 4800.75, 1500.00, 2200.99]‬

‭ Loop through the salaries list and print each number formatted with field width and precision‬
#
‭for salary in salaries:‬
‭print(f"{salary:>12.2f}")‬

‭ 9.Write a Python program to count the number of even numbers in a given set of n‬
1
‭numbers.‬

‭ Get the number of elements (n)‬


#
‭n = int(input("Enter the number of elements: "))‬

‭ Initialize the counter for even numbers‬


#
‭even_count = 0‬

‭ Loop through to get n numbers and check if each is even‬


#
‭for _ in range(n):‬
‭num = int(input("Enter a number: "))‬
‭if num % 2 == 0: # Check if the number is even‬
‭even_count += 1‬

‭# Output the count of even numbers‬


‭print(f"Total number of even numbers: {even_count}")‬

‭18. Write a Python program to evaluate the sequence: 1 + x + x‬‭2‬ ‭+ x‬‭3‬ ‭+ ⋯ + x‬‭n‭.‬ ‬

‭# Program to evaluate the sequence 1 + x + x^2 + x^3 + ... + x^n‬

‭ Get input values for x and n‬


#
‭x = float(input("Enter the value of x: "))‬
‭n = int(input("Enter the value of n: "))‬

‭ Initialize the sum‬


#
‭sequence_sum = 0‬

‭ Loop to calculate the sum of the sequence‬


#
‭for i in range(n + 1):‬
‭sequence_sum += x ** i‬

‭ Output the result‬


#
‭print(f"The result of the sequence 1 + x + x^2 + ... + x^{n} is: {sequence_sum}")‬

‭ 9. Write a Python program to find the sum of the cosine series‬


1
‭1 - x^2/2! + x^4/4!- .......‬

‭import math‬

‭# Program to find the sum of the cosine series 1 - x^2/2! + x^4/4! - ...‬

‭ Get input values for x and the number of terms (n)‬


#
‭x = float(input("Enter the value of x: "))‬
‭n_terms = int(input("Enter the number of terms to approximate the cosine series: "))‬

‭ Initialize the sum of the series‬


#
‭cosine_sum = 0‬

‭ Loop to calculate the sum of the series‬


#
‭for n in range(n_terms):‬
‭term = ((-1)**n * x**(2*n)) / math.factorial(2*n) # nth term in the series‬
‭cosine_sum += term‬

‭ Output the result‬


#
‭print(f"The sum of the cosine series for x = {x} with {n_terms} terms is: {cosine_sum}")‬
‭Or‬

‭# Program to find the sum of the cosine series 1 - x^2/2! + x^4/4! - ...‬

‭ Get input values for x and the number of terms (n)‬


#
‭x = float(input("Enter the value of x: "))‬
‭n_terms = int(input("Enter the number of terms to approximate the cosine series: "))‬

‭ Initialize the sum of the series‬


#
‭cosine_sum = 0‬

‭ Initialize the factorial variable‬


#
‭factorial = 1‬

‭ Loop to calculate the sum of the series‬


#
‭for n in range(n_terms):‬
‭# Calculate the power of x (x^(2n))‬
‭power_of_x = x ** (2 * n)‬

‭ Calculate the factorial (2n)!‬


#
‭if n > 0:‬
‭factorial *= (2 * n) * (2 * n - 1) # Efficient factorial calculation‬

‭ Calculate the nth term in the cosine series‬


#
‭term = ((-1) ** n * power_of_x) / factorial‬

‭ Add the term to the sum‬


#
‭cosine_sum += term‬

‭ Output the result‬


#
‭print(f"The sum of the cosine series for x = {x} with {n_terms} terms is: {cosine_sum}")‬

You might also like