Write a Python Program to Calculate Sum of Odd Numbers from 1 to N using While Loop, and For Loop with an example.
Python Program to Calculate Sum of Odd Numbers from 1 to N using For Loop
This Python program allows the user to enter the maximum value. Next, Python is going to calculate the sum of odd numbers from 1 to user-entered maximum value.
In this example, For Loop is used to keep the odd numbers are between 1 and maximum value.
TIP: I suggest you refer to Python Odd numbers from 1 to N article to understand the logic behind printing Odd numbers in Python.
# Python Program to Calculate Sum of Odd Numbers from 1 to N maximum = int(input(" Please Enter the Maximum Value : ")) Oddtotal = 0 for number in range(1, maximum+1): if(number % 2 != 0): print("{0}".format(number)) Oddtotal = Oddtotal + number print("The Sum of Odd Numbers from 1 to {0} = {1}".format(number, Oddtotal))
Python sum of odd numbers output
Please Enter the Maximum Value : 12
1
3
5
7
9
11
The Sum of Odd Numbers from 1 to 12 = 36
Python Program to display Sum of Odd Numbers from 1 to N without If
This Python sum of odd numbers program is the same as above. But, we used the third parameter inside the for loop to eliminate the If block.
# Python Program to Calculate Sum of Odd Numbers from 1 to N maximum = int(input(" Please Enter the Maximum Value : ")) Oddtotal = 0 for number in range(1, maximum+1, 2): print("{0}".format(number)) Oddtotal = Oddtotal + number print("The Sum of Odd Numbers from 1 to {0} = {1}".format(number, Oddtotal))
Python sum of odd numbers using a for loop output
Please Enter the Maximum Value : 15
1
3
5
7
9
11
13
15
The Sum of Odd Numbers from 1 to 15 = 64
Python Program to find Sum of Odd Numbers using While Loop
In this Python program, we replaced the For Loop with While Loop.
# Python Program to Calculate Sum of Odd Numbers from 1 to N maximum = int(input(" Please Enter the Maximum Value : ")) Oddtotal = 0 number = 1 while number <= maximum: if(number % 2 != 0): print("{0}".format(number)) Oddtotal = Oddtotal + number number = number + 1 print("The Sum of Odd Numbers from 1 to {0} = {1}".format(maximum, Oddtotal))
Python sum of odd numbers using a while loop output
Please Enter the Maximum Value : 20
1
3
5
7
9
11
13
15
17
19
The Sum of Odd Numbers from 1 to 20 = 100
Python Program to find Sum of Odd Numbers from 1 to 100
This Python example allows the user to enter Minimum and maximum value. Next, Python calculates the sum of odd numbers from Minimum to the maximum value.
# Python Program to Calculate Sum of Odd Numbers from 1 to 100 minimum = int(input(" Please Enter the Minimum Value : ")) maximum = int(input(" Please Enter the Maximum Value : ")) Oddtotal = 0 for number in range(minimum, maximum+1): if(number % 2 != 0): print("{0}".format(number)) Oddtotal = Oddtotal + number print("The Sum of Odd Numbers from {0} to {1} = {2}".format(minimum, maximum, Oddtotal))