this is my very first time asking a question on StackOverflow!
I am trying to write a code to know at what natural number the accumulated sum to the number becomes right before 10,000 using for and while loops in python.
a for loop,
accum_sum = 0
for n in range(10000):
if accum_sum > 10000:
print(n-1)
break
it gave me 140
and I was wondering how to write a code to get the same thing(140) by using a while loop ... this is what I tried but somehow it gave me a different answer. Can someone help me with this? I feel like I am lost
accum_sum = 0
while accum_sum < 10000:
n = 1
accum_sum = accum_sum n
if accum_sum > 10000:
print(n-1)
break
Thank you!
CodePudding user response:
In your code snippets:
- As @canton7 pointed out, in for you are never adding num to accum_sum and hence it will always be zero
- n is not defined before while, so you cannot increment it by 1 and will be thrown a NameError
Changing these and adding appropriate indentation should give you something like below.
Using for:
sum = 0
for num in range(0,10000):
sum = num
if num > 10000:
print('This is the number you want ', num-1)
break
Using while:
sum = 0
num = 0
while sum < 10000:
num = 1
sum = num
print('This is the number you want ', num-1)
Both of these print 140.
References: