Python - Cycle is an alternative to the while loop

1

Generic considerations:

  • I am currently programming in python ;
  • I have a relatively simple level code;
  • The code contains an instruction loop of type while loop ;

I would like to know if there is a way to run the code specified below with an instruction of type for loop , instead of while loop :

 soma = 0 
 i = 20 
 while i >= 0: 
   soma += -i 
   i = i - 2 
   print('Soma =',soma)
 print('/'*30)
 soma = 0
 i = 20

I'm doing this:

soma = 0
i = 20
for i in range(20, 0, -2):
  print('soma =', -i)

However, I do not get an output identical to the one I want

Thank you in advance for your help

    
asked by anonymous 12.05.2018 / 12:48

3 answers

5
soma = 0
i = 20
for i in range(20, 0, -2):
  soma += -i
  print('soma =', soma)
    
12.05.2018 / 14:58
2

If you just want the final result:

print('soma = ', sum(range(-20,0,2)))
    
12.05.2018 / 16:50
1

Well, I managed to solve it! Here is the code:

print('/'*30)
print('Ciclo FOR')
print('/'*30)

soma = 0
i = 20
for i in range(20, 0, -2):
  soma += -i
  print ('Soma =', soma)
    
12.05.2018 / 16:49