0

How to program the following on python

How to compute the sum 1-2+3-4+.....+1999-2000 I tried n<=2000 for i in range(1,2001): print(n-i) But i dont get it how to even change the sign every time 1 number adds

11th Jun 2020, 2:57 PM
Elliot
7 Respuestas
+ 8
Elliot, you have not been far away from a good solution with your code, some typos, that result in problems. Here is your slightly reworked code: sum_ = 0 for i in range(1,2001): if i%2==0: sum_ = sum_ - i else: sum_ = sum_ + i print(sum_)
11th Jun 2020, 3:49 PM
Lothar
Lothar - avatar
+ 3
First assign sum=0..now, As you can see negative sign comes when the no. Is divisible by 2... So you can make condition that if i%2==0 then do sum=sum-i else sum=sum+i then print sum ... I hope it helps..🙃
11th Jun 2020, 3:00 PM
ANJALI SAHU
+ 1
Thank you all
11th Jun 2020, 3:27 PM
Elliot
0
Ok I still not get it why it doesn't work but I tried Sum=0 for I in range(1,2001): if i%2==0: sum=sum+1 else: sum=sun-I Print(sum) But it prints 0
11th Jun 2020, 3:12 PM
Elliot
0
sum(range(1, 2001, 2)) - sum(range(2, 2001, 2))
11th Jun 2020, 3:19 PM
Bilbo Baggins
Bilbo Baggins - avatar