Help with simple while summation program

Asked

Viewed 720 times

2

Gentlemen,

I started to introduce the programming and the master is requesting an exercise as follows:

Write a Python script that asks the user to enter an integer, n, and computes the sum 1 + 2 + ... + n, if n > 0, -1 + -2 + ... + n, if n < 0. If n = 0, the sum is zero.

Use a single while cycle to calculate the sum.

Examples of interaction:

Example 1:

Enter the limit: 0 Sum = 0

Example 2:

Enter the limit: 3 Sum = 6

Example 3:

Enter the limit: -3 Sum = -6

Your programme must scrupulously respect the examples submitted, both as regards the form to request the data, how to present the results. The values shown in examples are only illustrative: your program must accept any integer.

Assume that the input data is always correct, i.e., that the number entered is always an integer.

I’m locked and I can’t move forward, I’ve reached the following algorithm:

n = int(input('Introduza o limite: '))
Soma = 0
while (n != 0):
    if n > 0:
     Soma += n
     n-=1

    else:
     Soma -= n
     n+=1    

print ('Soma = ', Soma)

So I can get to the result of Example 1 and Example 2, now when I try to get the result out as in Example 3, the number is always positive. What am I doing wrong? Thank you.

1 answer

1

Rodrigo, the problem is only at the moment of adding up the value of n negative, you are subtracting. Even if the number is negative, you must perform a sum calculation:

n = int(input('Introduza o limite: '))
soma = 0

while (n != 0):
  if n > 0:
    soma += n
    n-=1

  else:
    soma += n
    n+=1

print ('Soma = ', soma)
  • Daniel, I don’t quite understand what went wrong, could you explain to me better?

  • Rodrigo, put in the calculator 0 + (-1) and 0 - (-1) and you will notice the difference. As it was, it occurred that (-) and (-) became (+) and its number became positive.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.