Reputation: 41
I started to learn Python and I am stucked in lesson. I need to create program, where you at first asked for insert digit (you insert for example "5") and result should be sum of digits starting from 1 up to this digit you inserted (in this example 1+2+3+4+5). I created a program which is listing numbers up to inserted digit, but I cannot finish it - to create sum of those digits. Here is my code:
print ("Insert the digit")
digit = int(input())
i = 0
while i < (digit):
i = i + 1
print (i)
Upvotes: 1
Views: 450
Reputation: 9413
You can try following:
i = 0
total = 0
while i < digit:
i = i + 1 # can be i += 1
total = total + i # can be total += i
print (total)
range
function can also be used. You can read about this.
Upvotes: 3
Reputation: 142226
As others have pointed out, you're not keeping a running total, you can however use a maths trick here, eg:
n = int(input('Enter digit: '))
print('Total sum is:', int(n*(n/2 + .5)))
This'll be far more efficient for larger n
... so instead of building a generator and summing each at a time, you can use that formula to calculate in constant time any value of n
.
Upvotes: 5
Reputation: 5054
A really pythonic way would be to do the following:
print ("Insert the digit")
digit = int(input())
i = 0
while i < (digit):
i = i + 1
print (i)
summed = sum(range(digit+1))
print(summed)
Note: You should not use the variable name sum because that is a reserved symbol (language intern)
Upvotes: 0
Reputation: 19763
you can use sum with range:
my_sum = sum(range(1,digit+1))
range will give you list of integers, syntax range([start],stop)
,it will ends always one less, see the demo below
demo:
>>> range(10)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> range(1,10)
[1, 2, 3, 4, 5, 6, 7, 8, 9]
demo for sum
:
>>> my_num = range(1,10)
>>> my_num
[1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> sum(my_num)
45
Upvotes: 3
Reputation: 52181
You can also try
print ("Insert the digit")
digit = int(input())
print(sum(range(digit+1)))
Here range
is a function which will list all the numbers from 0
to digit
and sum
will calculate the total of them
Upvotes: 0