Sum Negative, Even, and Odd Numbers in a List Using Python
In this tutorial, we will learn how to program "Sum Negative, Even, and Odd Numbers in a List Using Python." The objective is to print the sum of negative, even, and odd numbers in a list. This tutorial will guide you step by step through methods for displaying the values of a list. By the end of this tutorial, you will have a solid understanding of how to implement this task effectively in Python, helping you strengthen your problem-solving abilities and improve your coding skills.
This topic is straightforward and easy to understand. Simply follow the instructions provided, and you will complete it with ease. The program will guide you step by step through the process of printing the sum of negative, even, and odd numbers in a list. So, let’s dive into the coding process!
Getting Started:
First you will have to download & install the Python IDLE's, here's the link for the Integrated Development And Learning Environment for Python https://www.python.org/downloads/.
Creating Main Function
This is the main function of the application. The following code will display a simple GUI in terminal console that will display program. To do this, simply copy and paste these blocks of code into the IDLE text editor.- while True:
- print("\n============ Sum Negative, Even, and Odd Numbers in a List ============\n")
- n = int(input("Enter the number of elements to be in the list: "))
- b = []
- for i in range(n):
- a = int(input("Element: "))
- b.append(a)
- sum_even = 0
- sum_odd = 0
- sum_neg = 0
- for j in b:
- if j > 0:
- if j % 2 == 0:
- sum_even += j
- else:
- sum_odd += j
- else:
- sum_neg += j
- print("Sum of all positive even numbers:", sum_even)
- print("Sum of all positive odd numbers:", sum_odd)
- print("Sum of all negative numbers:", sum_neg)
- # Ask user if they want to try again
- opt = input("\nDo you want to try again? (yes/no): ").strip().lower()
- if opt == "no":
- print("Exiting program...")
- break
- elif opt != "yes":
- print("Invalid choice. Exiting program...")
- break
This program takes a list of integers from the user and calculates three separate sums: the sum of all positive even numbers, the sum of all positive odd numbers, and the sum of all negative numbers. It iterates through the list, categorizes each number, and updates the corresponding sum. The results are then displayed, and the user is prompted to repeat the process or exit the program.
Output:
There you have it we successfully created Sum Negative, Even, and Odd Numbers in a List Using Python. I hope that this simple tutorial help you to what you are looking for. For more updates and tutorials just kindly visit this site. Enjoy Coding!
More Tutorials for Python Language