While Loop Break Continue in Python by CodingXpertz

Published: 18 February 2023
on channel: 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.


On this page of the site you can watch the video online While Loop Break Continue in Python by CodingXpertz with a duration of hours minute second in good quality, which was uploaded by the user Coding Xpertz 18 February 2023, share the link with friends and acquaintances, this video has already been watched 9 times on youtube and it was liked by 1 viewers. Enjoy your viewing!