While Loop Break Continue in Python by CodingXpertz

Publicado em: 18 Fevereiro 2023
no canal de: Coding Xpertz
9
1

Previously I talked about how you can loop with for. We can also continue looping as long as a
condition is true with a while loop. While loops are used when you don't know how many times
you will have to loop.
Here we’ll generate a random number with the random module and randrange(). We will then
use the while loop to guess the random value and output it.
CODE
We can use the random module to generate random numbers
import random


Generate a random integer between 1 and 50
rand_num = random.randrange(1, 51)


The value we increment in the while loop is defined before the loop
i = 1


Define the condition that while true we will continue looping
while (i != rand_num):


You must increment your iterator inside the while loop
i += 1


Outside of the while loop when we stop adding whitespace
print("The random value is : ", rand_num)
Break & Continue
Break and continue are very useful. Continue stops executing the code that remains in the loop
and jumps back to the top. While break ends execution and jumps directly to the code that lies
immediately outside of the loop.
Here we’ll cycle from 0 to 20 with a while loop. If a number is even will use continue to skip
printing it. If it is odd we’ll print it. We’ll then end execution with break if the value ever reaches
15.


Nesta página do site você pode assistir ao vídeo on-line While Loop Break Continue in Python by CodingXpertz duração hora minuto segundo em boa qualidade , que foi baixado pelo usuário Coding Xpertz 18 Fevereiro 2023, compartilhe o link com seus amigos e conhecidos, no youtube este vídeo já foi visto 9 vezes e gostou 1 espectadores. Boa visualização!