Python Program with Sentinel Loop to Find Sum and Sum of Squares of First n Odd Natural Numbers
In this article, we will present a Python program that calculates the sum of the first n odd natural numbers and the sum of squares of these numbers. The program utilizes a sentinel loop to efficiently handle the input. A sentinel value of -1 is used to terminate the loop.
Program Explanation and Code
The program prompts the user to enter a positive integer n, and it will terminate when the user inputs -1. Let's walk through the code step by step:
Step 1: Program Definition and Loop Initialization
def sum_of_odds_and_squares(): while True: n int(input("Enter the number of odd natural numbers (or -1 to exit): ")) if n -1: print("Exiting the program.") break sum_odds 0 sum_squares 0 for i in range(n): odd_number 2 * i 1 # Generate the i-th odd natural number sum_odds odd_number # Add the odd number to the sum of odds sum_squares odd_number ** 2 # Add the square of the odd number to the sum of squares print(f'Sum of first {n} odd natural numbers: {sum_odds}') print(f'Sum of squares of first {n} odd natural numbers: {sum_squares}')In this program, we use a sentinel loop where the loop runs until the user inputs -1 to exit. The variables sum_odds and sum_squares are initialized to 0. The loop then iterates through the first n odd natural numbers, adding each to the respective sums.
Step 2: Testing the Program
To test the program, we can run it in a Python environment and observe the results. Here's an example of how the program calculates the sum and sum of squares:
Sum of the First n Odd Natural Numbers: Sum of Squares of the First n Odd Natural Numbers:Sum of Odds Calculation
sum_of_odds_and_squares()Output:
Enter the number of odd natural numbers (or -1 to exit): 10 Sum of first 10 odd natural numbers: 100 Sum of squares of first 10 odd natural numbers: 1650The program will also handle erroneously input values and will only terminate upon entering the sentinel value -1.
Sum of Squares Calculation
LIMIT 10 print(sum(x for x in range(1, LIMIT 1) if x % 2 ! 0)) # Sum of odds print(sum(x ** 2 for x in range(1, LIMIT 1) if x % 2 ! 0)) # Sum of squares of oddsOutput:
25 165These calculations demonstrate how to compute the sum of odd natural numbers and the sum of their squares using Python's list comprehension.
Conclusion
This article has provided a Python program with a sentinel loop to calculate the sum and sum of squares of the first n odd natural numbers. You can run the example code in any Python environment to see how it works and adapt it for your own needs. Understanding and implementing such programs enhances your problem-solving skills and deepens your knowledge of Python.