Reputation: 17
I want to take user input and add each number up to 0. For example user inputs 9
I want to add 9+8+7+6.... +1 and output the total. My code
def main(*args):
sum = 0
for i in args:
sum = i + (i - 1)
return sum
result = main(9)
print(result)
comes close, but I can't get it to iterate through until 0. I've tried adding ranges in a few ways but no luck there. I'm stuck.
Upvotes: 0
Views: 275
Reputation: 9441
Nth triangle number. No iteration needed.
def calculate_nth_triangle_number(value):
return value * (value + 1) / 2
Upvotes: 2
Reputation: 25023
Your code misuses a relatively advanced feature of Python, that is argument packing, where all the arguments supplied to a function are packed in a tuple.
What happens when you call main(9)
? the loop is entered once (because calling the function with a single argument is equivalent to args = (9, )
in the body of the function) i
takes only one value, i = 9
and you have sum = 9+8 = 17
.
For your case I don't like a for
loop, can you use a while
loop? with a while
your function follows exactly the definition of your task!
def my_sum(n):
result = 0
while n>0:
result = result + n
n = n - 1
return result
Note that the order of summation and decrease is paramount to a correct result... note also that sum
is the name of a built-in function and it is considered bad taste to overload a built-in name with an expression of yours.
Upvotes: 0
Reputation: 9019
Let's say the user input is assigned to x
, then the most simplistic answer is:
sum(range(int(x)+1))
Note that range()
will generate a list (actually, an immutable sequence type in Python 3) of numbers up to, but not including, x
, hence the +1
.
In terms of your original code, there are a few issues. First, you should avoid naming variables the same as Python built-ins, such as sum
. Second, you are attempting to iterate through a tuple of input arguments (e.g. args = (9,)
in your case), which will perform 9 + (9-1)
, or otherwise 17
and then return that sum as an output.
Instead, you could do something like:
def main(*args):
mysum = 0
for i in range(args[0]+1):
mysum = mysum + i
return mysum
result = main(9)
print(result)
Both solutions here will return 45
.
Upvotes: 2