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.
Auf dieser Seite können Sie das Online-Video While Loop Break Continue in Python by CodingXpertz mit der Dauer stunde minuten sekunde in guter Qualität ansehen, das der Benutzer Coding Xpertz 18 Februar 2023 hochgeladen hat, den Link mit Freunden und Bekannten teilen, dieses Video wurde auf Youtube bereits 9 Mal angesehen und es wurde von 1 den Zuschauern gefallen. Viel Spaß beim Betrachtenden Zuschauern gefallen!