In this tutorial I will show you how to calculate the sum of odd and even numbers in Python.
CODE:
#Sum of even & odd numbersnumbers=[14,55,72,62,87,64,20]evenTotal=0oddTotal=0for number in numbers:if(number % 2== 0):evenTotal += numberelse:oddTotal += numberprint("The sum of Even Numbers=", evenTotal)print("The sum of Odd Numbers=", oddTotal)
Explanation:
We're going to use a for loop to iterate and to calculate the sum of even and odd numbers. So we have to define the variable as evenTotal & oddTotal and set it to 0.
For each iteration check if the number is divisible by 2 with no remainder, then it is even and add it the variable evenTotal. If it leaves a remainder 1 then the number is odd and then add it to the variable oddTotal.
The plus is the assignment operator is used to adding the total of all even and odd numbers. After our for loop. This totalOdd, totalEven variables has the total of all even and odd numbers. we can simply print it here.
cmd:python example.py
OUTPUT:
The sum of Even Numbers= 232
The sum of Odd Numbers= 142
Post your comments / questions
Recent Article
- How to Enable Virtualization in BIOS Security Settings in Intel Processors For Android Studio?
- Dependency 'androidx.activity:activity:1.8.0' requires libraries and applications that depend on it.
- AttributeError: 'NoneType' object has no attribute 'get_text' - Python
- ModuleNotFoundError: No module named 'openpyxl' - Python
- How to get thumbnail from vimeo video URL in Python?
- Remove all special characters, punctuation except spaces from string - Python
- OSError: cannot write mode RGBA as JPEG- Python
- expected str, bytes or os.PathLike object, not JpegImageFile - Python
Related Article