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.
In questa pagina del sito puoi guardare il video online While Loop Break Continue in Python by CodingXpertz della durata di ore minuti seconda in buona qualità , che l'utente ha caricato Coding Xpertz 18 febbraio 2023, condividi il link con amici e conoscenti, su youtube questo video è già stato visto 9 volte e gli è piaciuto 1 spettatori. Buona visione!