-2

The question was tp :write a program to find the sum of n natural numbers using while loop in python.

n = int(input("Enter a number: "))
i = 1
while i<n:
    print(i)
    i = i + 1

this is what I have done s far... can not understand what to do next.

rioV8
  • 24,506
  • 3
  • 32
  • 49
Babrik Warsi
  • 9
  • 1
  • 1
  • 1

5 Answers5

1
n = int(input("enter a number: "))
i = 1
sum = 0
while (i <= n):
    sum = sum + i
    i = i + 1
print("The sum is: ", sum)
UTSAV ADDY
  • 11
  • 1
  • Don't use `sum` as variable name, because it will shadow the built-in function `sum`: https://docs.python.org/3/library/functions.html#sum – Gino Mempin Jun 23 '22 at 22:21
0

with a while loop the sum of natural numbers up to num


num = 20
sum_of_numbers = 0
while(num > 0):
    sum_of_numbers += num
    num -= 1
print("The sum is", sum_of_numbers)
Alasgar
  • 134
  • 9
  • 1
    its not good to name variables over inbuilt python functions, I would suggest naming sum something else, maybe s? – Emi OB Nov 22 '21 at 13:03
  • 1
    You do not prompt for a number input and your first if is useless - is that code auto generated? – luk2302 Nov 22 '21 at 13:03
0

You can either follow Alasgar's answer, or you can define a function with the formula for this particular problem.
The code's gonna be something like this:

def natural(n):
    sumOfn = (n * (n + 1))/2

terms = int(input("Enter number of terms: "))
natural(terms)
NameError
  • 206
  • 1
  • 3
  • 19
0

number = int(int(input("Enter the number: "))

if number < 0:

print("Enter a positive number: ")

else:

totalSum = 0
while (number > 0):
    totalSum += number
    number -= 1
    print ("The sum is" , totalSum)
0
num = int(input('Enter the number : '))
sum = 0
while 0<num:
    sum += num
    num -= 1
print(f'The sum of the number is {sum}')
Seven
  • 1
  • 1
  • 2
    This answer was reviewed in the [Low Quality Queue](https://stackoverflow.com/help/review-low-quality). Here are some guidelines for [How do I write a good answer?](https://stackoverflow.com/help/how-to-answer). Code only answers are **not considered good answers**, and are likely to be downvoted and/or deleted because they are **less useful** to a community of learners. It's only obvious to you. Explain what it does, and how it's different / **better** than existing answers. [From Review](https://stackoverflow.com/review/low-quality-posts/32598590) – Trenton McKinney Aug 29 '22 at 20:26