Sum of even and odd numbers in python using while loop

Python program to calculate sum of odd and even numbers

Python program to calculate sum of odd and even numbers

Contents

  • 1 Python program to calculate sum of odd and even numbers
    • 1.1 What is even or odd numbers?
    • 1.2 Calculate the sum of odd and even numbers using for loop
    • 1.3 Calculate the sum of odd and even numbers using while loop
    • 1.4 Related posts:

In this tutorial, we will discuss The Python program to calculate sum of odd and even numbers

In this article, we are going to learn the concept of how to  calculate the sum of odd and even numbers in the Python language

What is even or odd numbers?

When any integer value which ends in 0,2,4,6,8 is divided by two it is called as an even number

Example for even numbers : 34,-62,58,890

When any integer value which ends in 0,1,3,5,7,9 is not divided by two it is called as an odd number

Example for  odd numbers : 21,567,-57,67

We can use a modular operator to find odd or even number in the given range.

if n%2==0,  n is an even number

if n%2==1,  n is an odd number

Calculate the sum of odd and even numbers using for loop

Program 1

This program allows the user to enter a maximum number of digits and then, the program will sum up to odd and even numbers from the from 1 to entered digits using a for loop.

#Python program to calculate sum of odd and even numbers using for loop
max=int[input["please enter the maximum value: "]]
even_Sum=0
odd_Sum=0

for num in range[1,max+1]:
    if [num%2==0]:
        even_Sum=even_Sum+num
    else:
        odd_Sum=odd_Sum+num

print["The sum of Even numbers 1 to {0} = {1}".format[num,even_Sum]]
print["The sum of odd numbers 1 to {0} = {1}".format[num,odd_Sum]]

case 1

please enter the maximum value: 10
The sum of Even numbers 1 to 10 = 30
The sum of odd numbers 1 to 10 = 25

case 2

please enter the maximum value: 100
The sum of Even numbers 1 to 100 = 2550
The sum of odd numbers 1 to 100 = 2500

Calculate the sum of odd and even numbers using while loop

Program 2

This program allows the user to enter a maximum number of digits and then, the program will sum up to odd and even numbers from the from 1 to entered digits using a while loop.

#Python program to calculate sum of odd and even numbers using while loop
max=int[input["please enter the maximum value: "]]
even_Sum=0
odd_Sum=0

num=1
while [num 0: print["This is an odd number. "] else: print["This is an even number. "]

Chủ Đề