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.
Daniel, I don’t quite understand what went wrong, could you explain to me better?
– Rodrigo Girardon
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.
– Daniel Mendes