How to use While in Python 3?

Asked

Viewed 84 times

-4

My doubt is about the bow while, I can’t understand how it works.

Write a Python function that takes, by argument, two integers and returns the sum of all integers between the two (including the two).

my code...

def somatorio(x,y):
    count = 0
    soma = 0

    while count < y:
        soma = y + (y-count)
        count += 1
    return soma

print(somatorio(1,2))
print(somatorio(1,5))
  • 1

    What do you want to know specifically? You used something you don’t know what it’s for?

  • was about the condition, the doubt has already been resolved, thank you ^^

  • Just for the record, this code is wrong, because it doesn’t return "the sum of all the integers between the two", should look something like this: https://ideone.com/6b1iuW <-- this link also has other options how to do

1 answer

0


The while is a repeat loop. It causes a set of instructions to be executed while a condition is true. When this condition ceases to be true, the loop is stopped, see example below:

contador = 0
while(contador < 10):
    print(contador)
    contador = contador + 1

In the above example, we create a loop that executes the command print for 10 times. To create a variation, or an infinite loop - widely used in game development - we can do so:

while(True):
    print("infinito")
  • Thank you very much, that part of the condition that was catching me...

Browser other questions tagged

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