How to Find the Sum of Natural Number in Python

In this tutorial, we’ll learn how to program "How to Find the Sum of Natural Numbers in Python." We’ll focus on calculating the sum of natural numbers accurately. The objective is to achieve a correct calculation that will display the sum of the natural numbers. I'll provide a sample program to demonstrate the coding process, making it easy to understand and implement. So, let’s get started with coding!

This topic is straightforward to understand. Just follow the instructions I provide, and you'll be able to complete it with ease. The program I'll show you demonstrates the correct way to find the sum of natural numbers. I'll also provide a simple and efficient method to achieve this effectively. So, let’s start coding!

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.
  1. while True:
  2.    print("\n================= Find the Sum of Natural Number =================\n\n")
  3.  
  4.  
  5.    num = int(input("Enter a number: "))
  6.  
  7.    if num < 0:
  8.       print("Enter a positive number")
  9.    else:
  10.       sum = 0
  11.  
  12.       while(num > 0):
  13.           sum += num
  14.           num -= 1
  15.       print("The sum is", sum)
  16.  
  17.    opt = input("\nDo you want to try again?(yes/no): ")
  18.  
  19.    if opt.lower() == 'yes':
  20.       ret=False
  21.    elif opt.lower() == 'no':
  22.       ret=True
  23.       print("Exiting program....")
  24.    else:
  25.       print("Please enter yes/no:")
  26.       break
  27.  
  28.    if ret == False:
  29.       continue

This program calculates the sum of natural numbers up to a user-specified positive integer. When a number is entered, the program checks if it’s positive. If negative, it prompts the user to enter a positive number. For positive inputs, it calculates the sum from that number down to 1 using a while loop. After displaying the result, the program asks if the user wants to try again. If the answer is "yes," it repeats the process; if "no," it exits gracefully. An invalid response prompts the user to re-enter "yes" or "no."

Output:

There you have it we successfully created How to Find the Sum of Natural Number in 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

Python Tutorials

Add new comment