Python - Cycle for as an alternative to the while cycle

Asked

Viewed 502 times

2

General considerations:

  • I am currently programming in python;
  • I have a relatively simple level code;
  • The code contains an instruction cycle of the 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 like this:

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

However, I do not get the same output as desired

I thank you in advance for your help

3 answers

6


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

3

If you just want the end result:

print('soma = ', sum(range(-20,0,2)))

1

Well, I figured it out! 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)

Browser other questions tagged

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