Codecademy Python Tutorial #21

**Creating a Loop: The While Loop**

In programming, loops are essential tools that allow us to repeat a set of instructions multiple times. One common type of loop is the while loop, which continues to execute a block of code as long as a certain condition is met. In this article, we'll explore how to create a while loop in Python.

**The Basics of a While Loop**

A while loop works by continuously checking a condition until it's no longer true. Once the condition becomes false, the loop stops executing. The basic structure of a while loop consists of three parts: a condition, a block of code, and an increment or decrement statement. The condition is evaluated at the beginning of each iteration, and if it's met, the code in the block is executed. After that, the increment or decrement statement updates the value used in the condition, causing the loop to repeat.

**Using a While Loop**

Let's consider an example where we want to create a loop that continues to ask the user for their guess until they correctly guess a randomly generated number between 1 and 10 (inclusive). We'll use a variable `guessesLeft` to keep track of how many attempts the user has left. Initially, `guessesLeft` is set to 3, representing three chances to get it right.

```python

guesses_left = 3

while guesses_left > 0:

# code here

```

In this case, we've started with a condition that will be evaluated at the beginning of each iteration. If `guessesLeft` is greater than 0, the loop continues to execute. This is where our block of code comes in – let's ask the user for their guess and check if it matches the randomly generated number.

```python

guess = int(input("Please enter your guess: "))

```

This line asks the user to input a guess, converts the input into an integer (since we're dealing with whole numbers), and stores it in the `guess` variable. We'll use this variable to compare against our randomly generated number.

```python

random_number = 5 # for example

if guess == random_number:

print("You win!")

else:

print("You lose.")

```

Here, we're checking if the user's guess matches the randomly generated number. If it does, we congratulate them and exit the loop. Otherwise, we tell them they lost.

```python

guesses_left -= 1

```

This line decrements `guessesLeft` by one after each iteration. This updates our condition for the next iteration, allowing us to keep track of how many chances the user has left.

**Putting it All Together**

Now that we've broken down the components of a while loop, let's put them together into a complete example:

```python

guesses_left = 3

while guesses_left > 0:

random_number = int(input("Please enter your guess: "))

if random_number == 5: # for example

print("You win!")

break

else:

print("You lose.")

guesses_left -= 1

```

This code creates a loop that continues to ask the user for their guess until they correctly guess our randomly generated number. Once they get it right, the loop stops executing.

**Additional Tips and Considerations**

When working with while loops, it's essential to consider the condition that will terminate the loop. This is typically done by decrementing or incrementing a counter variable in each iteration, ensuring that the condition becomes false eventually.

In this example, we've used `guessesLeft` as our counter variable, but you could use any variable name and data type that suits your needs.

Also, remember to handle potential errors, such as invalid input from the user. You can do this by adding error-checking code before evaluating the condition in the while loop.

**Practicing While Loops**

Now that you've learned how to create a while loop, it's time to put your skills into practice! Try writing some of your own while loops using different conditions and scenarios. Share your code with others in the comments below, and I'll be happy to review it and provide feedback.

**Conclusion**

While loops are an essential tool for any programmer, mastering them takes practice and patience. By understanding how to create a while loop and when to use it, you can write more efficient and effective code. Remember to consider your condition carefully, handle potential errors, and practice writing while loops until they become second nature. Happy coding!

"WEBVTTKind: captionsLanguage: enwhat is uh people of the world how are you doing this fine morning we left off at infinite loops oh where are my manners this is qazi from cleverprogrammer.com and you are watching codecademy python tutorial number 21 okay awesome now that we got out of the way how are you doing hopefully you're doing awesome we back to where we were supposed to be we are part five infinite loops okay we just finished talking about infinite loops infinite loops was this concept of horrible destruction and your code running forever i showed you that my browser just crashed and that was terrible and it can cause problems in your computers too however it's fun you can do that to your friends write the uh open up their terminals write an infinite loop and then watch them struggle um but don't do that to maybe you're really close do that maybe two only you're really close friends not your acquaintances so we found out what's wrong with infinite loops and what are some common errors that can cause it for example not paying attention to if this is a less than sign or greater than sign right not paying attention to whether you're incrementing it and decrementing it that can cause a problem right for example if you want to go if you want to go less less less less less to meet your condition let's say you got to get all the way down to zero and you're currently at 10 you want to keep going and reaching zero so you want to decrement right go down to zero but if you get confused and you write a plus one there and you keep going 10 11 12 13 14 and so on and so forth now you're going in the wrong direction you're gonna run an infinite loop okay let's click start next lesson break so here we're going to talk about breaks breaks generally avoid them okay my advice to you generally means bad logic you didn't account for something can 99.99 percent of the times be avoided with the right logic however it's a simpler way to let you break out of things right it's sometimes useful if you really need to use it break is a one-line statement that means exit the current loop so yeah it just by it just forces the loop to end without relying on some kind of logic it just goes break okay so here what we're saying if i'm reading this code is a while true which means just run forever there's nothing that can change this true right you it's not a variable you can't say right you can't go true it true is equal to false that won't work it's kind of like saying 5 is equal to false you can't assign to these things and it'll just keep running forever okay so actually let me check if i'm what i'm saying is actually true yeah so it's a keyword you can't assign to a keyword okay now what happens in this loop well we print count count is zero the first time then we increment count by one and then we check hey is count greater than or equal to 10 meaning it's count 10 or 10 11 12 13 all up to infinity it goes no that's not the case because count is zero the first time right so it's zero and this condition evaluates to false which is why this part of the loop up with this part of this condition does not run if it did run it'll exit the loop eventually count keeps getting incremented we get it to be nine eventually count is 10. it prints out 10 to the screen it says 10 is equal to 10 plus 1 which makes count 11. count is now 11. just just recall that plus equals is the same thing as count plus one okay that's how you should try to write it for now and here we're saying if 11 is greater than or equal to 10 this is a true statement we break and we end the loop okay that's what that means so first create a blah blah the simplest way shown using an if statement you define the stopping condition so here's our stopping condition but do notice we still have a stopping condition that we're using here right and inside the if you write break meaning exit the loop break just means exit the loop the difference here is that this loop is guaranteed to run at least once so this is a way you can guarantee to run a loop at least once kind of like do while loop in java or c c plus plus because remember sometimes your loop might not run at all right like if you had a condition while count is greater than 10 what if count was a hundred your loop will not run so if you wanted your loop to run definitely at least one time for whatever reason then this would be the way to go about it i still don't like it you should try to avoid it see what the break does feel free to mess around with it but make sure you don't cause an infinite loop click save and submit code when you're ready to continue let's save and submit so we've figured out what it does while slash else so you can combine an else statement with the while loop this is actually something for some reason i recently learned because it's pretty esoteric at least i don't see it much being used and i was solving a problem programming problem and i saw that you can combine the else statement with a while loop you can also combine an else statement with a for loop just like um you can combine else with the if statement so how does how that works is if the while condition is ever false and you break out of the loop then you just run the else part okay so let's check it out and how it works so we're gonna just run it a few times sometimes before you even read it if you know generally it's a good idea to try to walk through it before you run it but sometimes just run it and see what it does and then you can start to get an idea of it all the print statements right these are python 2 print statements i'm converting it to python 3 so we can run it properly let's check it out print another print statement okay hopefully all right lucky numbers three numbers will be generated if one of them is a five you lose one three six none of them was a five two four two we win two one two six we win four one four we went geez it's never five huh okay sorry so we finally lost how does this work okay so let's come down to the part where it says while and the else part okay so if count is not less than three right if this statement ever evaluates to a false right then what happens what if count is currently not less than three but three itself that means the loop has already run how many times three times right i think they do that in german or something or when they ask for drinks or whatever they go like this like get me three drinks i don't know they do that somewhere correct me um i'm a little geographically challenged so okay so zero one and two is effectively runs three times so if the while the count ever gets to three from zero that means it's run three times already and then it goes while three is less than three three is not less than 3 that evaluates to a false so then it sends you to the part where it says you win okay so here's how it works if we randomly generate a number between 1 and 5 rand int the function randint right here randint it does not include the endpoints it goes from the start up to but not including the last part for example if i copy this code and i open up my python terminal doesn't matter 2.7 python 3.4 it does not matter and i just run this right so i import the random module that people wrote while getting their relationships destroyed and eating ramen noodle in hundreds and thousands of hours you just stole their code by writing in one line oh um the other way random ran in does include it ran range does not include it okay so you'll never get a six if i do two here you'll never get a two you'll just get a one forever so randint actually does include it what i should like learn my python right i don't understand it so again these are one of those things i'm glad these these things get caught on camera and i won't edit them out because this is so common right they asked einstein how many feet are in a mile and he goes i don't know and he says i don't care because i don't want to use my brain to memorize a bunch of irrelevant facts i want to use it to think so here i don't want to just memorize everything usually what programmers do is even programmers who program every day you know and we do it as a job will if all almost always go and look it up some documentation just to make sure that what they're doing they're doing it correctly okay so these things not everybody has them memorized so that's why you refer to the documentation and just double check so anyways this will guess a number from one to six including one and six then it gets printed out if that number that was guessed was five then it goes you lose and it breaks out of the loop and everything stops if this uh and then after all of that it just increments count by one okay so if obviously this if condition hasn't run if count ever gets incremented by one obviously the if condition hasn't run because if it had the loop would have been over and you would have never gotten to line 14. then it goes again generates a number if it was not five then it increments count by one if it was not five again it'll increment count by one eventually when count is first time count is zero then it's one then it's two and if it hasn't met this if condition and uh it hasn't evaluated to true for the first three times of the loop then you this part evaluates to a false and you get to the else part of the loop and it says you went okay so let's go back and just run it so we made sure we understood it then just run it and go okay all right we're done your own while else so now we write our own now you should be able to make a game similar to the one in the last exercise the code from the last exercise is below so you guess guess guess if you don't guess correctly you lose eventually after a certain number of times uh and you do guess is equal to intra input which means that i take your input and i convert it to a string right so here right instead if i did int it won't actually show you but if i do let's say user is equal to this and i say five and i do type of user so what type of what was the type of the answer and if i just print that user it'll show you that it's five and it says the type is int but if i don't wrap it in integer function then what it shows you effectively is uh if i do user it shows you that it's a string five right and if i do type of user and it's a string type not an type which is why you need to wrap it into an integer function remember raw input turns user input into a string we use int to make it a number again okay so that's essentially what's going on there use a while loop to get the user to let the user keep guessing so long as guess is left is greater than zero so while is greater than zero keep running which means that we're probably going to be decrementing it every single time right just to think about it if guess is left is three next time guess is left is two then it's one then it's zero meet some kind of condition and then loop should stop ask the user for their guess just like the example above if they guessed correctly print break let's start coding this up so we're going to say while guesses left is greater than zero and i'm just gonna write this part right here for now left minus equal one sometimes i just write this part right away so i know my loop will stop at some point because i do know i want to make it stop and i don't want an infinite loop so i write my breaking condition right away and then i'll like most of the times write my code in between that so i'll write my code for example now here because i know i'm safe and my loop will stop okay so use a all right ask the user for their guess i'll say guess is equal to ant raw input and i will say please enter your guess this little space is nice so user can type when the user is about to type their cursor is blinking where my cursor is right now but if i didn't have the space their cursor would be where my cursor is right now that would look weird i also put the colon here because sometimes people will do this and it's weird when it says please enter your guess end of sentence and you're typing right there it's a little confusing so colon makes more sense it's a better user interface two parentheses to close off the right input function parentheses and then the second parenthesis to close off the integer int function parentheses okay if they guess correctly print you in okay so if guess is equal equal to uh the random number that was generated then print you win okay and then break out of the loop okay else print you lose okay so this part what happens it keeps running and then once the the wild condition evaluates to once the wild condition evaluates stuff falls it prints out this part let's step through the code line by line guess is this so the user gets to type in something once that user types in something it goes hey let me see if your guests match the random number that i picked from 1 to 10 inclusive so let's say the random number was 5. so it goes let's see if you put in 3 is that equal to 5 nope so it does not break out of the loop and it also does not say you win so we keep going you get to guess again and it decrements guesses left by one so guesses left initially was three then the next time will be two it goes here asks for the user input you put in a guess it checks if your guess was equal to the random number which again was probably five right we're not changing random number every time we picked it to be five initially and it stays as five the entire time the only thing is changing is guesses now let's say you guessed four so this part evaluates to false so it does not run the that block here goes to line 13. decrements guess is left by one so now guess is left uh goes from two to one eventually when guess is left is zero zero is not strictly greater than zero that evaluates to a false which means we go to the else part and uh you know none of this block of code runs we go to the else part and it just says you lose okay so that is it for that let's check it out uh please enter your guess we'll say three oh look at that i guess correctly the first time so the random number was actually three i had a one out of ten chance or sorry one two three one two three yeah yeah i'm not gonna count it i do know it's actually ten so i had a one out of ten chance to guess it right and i did all right now for loops so we just ended the section on while loops that's great so i think a perfect thing to do here is actually just end this video because we've completed a while loop section this way you get to practice some while loops in the comments below you can also put some while loops that you have made like actually put them down there and i'll comment and i'll tell you if they're wrong or if they're right or if they're cool and they'll also give other people an idea of what to do okay that way you guys can collaborate right here and if you um yeah so we're gonna continue from the next one so this is it this is qazi from cleverprogrammer.com if you enjoyed the video please give it a thumbs up subscribe make sure to subscribe so you can keep getting these amazing videos other than that i will see you in the next video codecademy python tutorial number 22. whooshwhat is uh people of the world how are you doing this fine morning we left off at infinite loops oh where are my manners this is qazi from cleverprogrammer.com and you are watching codecademy python tutorial number 21 okay awesome now that we got out of the way how are you doing hopefully you're doing awesome we back to where we were supposed to be we are part five infinite loops okay we just finished talking about infinite loops infinite loops was this concept of horrible destruction and your code running forever i showed you that my browser just crashed and that was terrible and it can cause problems in your computers too however it's fun you can do that to your friends write the uh open up their terminals write an infinite loop and then watch them struggle um but don't do that to maybe you're really close do that maybe two only you're really close friends not your acquaintances so we found out what's wrong with infinite loops and what are some common errors that can cause it for example not paying attention to if this is a less than sign or greater than sign right not paying attention to whether you're incrementing it and decrementing it that can cause a problem right for example if you want to go if you want to go less less less less less to meet your condition let's say you got to get all the way down to zero and you're currently at 10 you want to keep going and reaching zero so you want to decrement right go down to zero but if you get confused and you write a plus one there and you keep going 10 11 12 13 14 and so on and so forth now you're going in the wrong direction you're gonna run an infinite loop okay let's click start next lesson break so here we're going to talk about breaks breaks generally avoid them okay my advice to you generally means bad logic you didn't account for something can 99.99 percent of the times be avoided with the right logic however it's a simpler way to let you break out of things right it's sometimes useful if you really need to use it break is a one-line statement that means exit the current loop so yeah it just by it just forces the loop to end without relying on some kind of logic it just goes break okay so here what we're saying if i'm reading this code is a while true which means just run forever there's nothing that can change this true right you it's not a variable you can't say right you can't go true it true is equal to false that won't work it's kind of like saying 5 is equal to false you can't assign to these things and it'll just keep running forever okay so actually let me check if i'm what i'm saying is actually true yeah so it's a keyword you can't assign to a keyword okay now what happens in this loop well we print count count is zero the first time then we increment count by one and then we check hey is count greater than or equal to 10 meaning it's count 10 or 10 11 12 13 all up to infinity it goes no that's not the case because count is zero the first time right so it's zero and this condition evaluates to false which is why this part of the loop up with this part of this condition does not run if it did run it'll exit the loop eventually count keeps getting incremented we get it to be nine eventually count is 10. it prints out 10 to the screen it says 10 is equal to 10 plus 1 which makes count 11. count is now 11. just just recall that plus equals is the same thing as count plus one okay that's how you should try to write it for now and here we're saying if 11 is greater than or equal to 10 this is a true statement we break and we end the loop okay that's what that means so first create a blah blah the simplest way shown using an if statement you define the stopping condition so here's our stopping condition but do notice we still have a stopping condition that we're using here right and inside the if you write break meaning exit the loop break just means exit the loop the difference here is that this loop is guaranteed to run at least once so this is a way you can guarantee to run a loop at least once kind of like do while loop in java or c c plus plus because remember sometimes your loop might not run at all right like if you had a condition while count is greater than 10 what if count was a hundred your loop will not run so if you wanted your loop to run definitely at least one time for whatever reason then this would be the way to go about it i still don't like it you should try to avoid it see what the break does feel free to mess around with it but make sure you don't cause an infinite loop click save and submit code when you're ready to continue let's save and submit so we've figured out what it does while slash else so you can combine an else statement with the while loop this is actually something for some reason i recently learned because it's pretty esoteric at least i don't see it much being used and i was solving a problem programming problem and i saw that you can combine the else statement with a while loop you can also combine an else statement with a for loop just like um you can combine else with the if statement so how does how that works is if the while condition is ever false and you break out of the loop then you just run the else part okay so let's check it out and how it works so we're gonna just run it a few times sometimes before you even read it if you know generally it's a good idea to try to walk through it before you run it but sometimes just run it and see what it does and then you can start to get an idea of it all the print statements right these are python 2 print statements i'm converting it to python 3 so we can run it properly let's check it out print another print statement okay hopefully all right lucky numbers three numbers will be generated if one of them is a five you lose one three six none of them was a five two four two we win two one two six we win four one four we went geez it's never five huh okay sorry so we finally lost how does this work okay so let's come down to the part where it says while and the else part okay so if count is not less than three right if this statement ever evaluates to a false right then what happens what if count is currently not less than three but three itself that means the loop has already run how many times three times right i think they do that in german or something or when they ask for drinks or whatever they go like this like get me three drinks i don't know they do that somewhere correct me um i'm a little geographically challenged so okay so zero one and two is effectively runs three times so if the while the count ever gets to three from zero that means it's run three times already and then it goes while three is less than three three is not less than 3 that evaluates to a false so then it sends you to the part where it says you win okay so here's how it works if we randomly generate a number between 1 and 5 rand int the function randint right here randint it does not include the endpoints it goes from the start up to but not including the last part for example if i copy this code and i open up my python terminal doesn't matter 2.7 python 3.4 it does not matter and i just run this right so i import the random module that people wrote while getting their relationships destroyed and eating ramen noodle in hundreds and thousands of hours you just stole their code by writing in one line oh um the other way random ran in does include it ran range does not include it okay so you'll never get a six if i do two here you'll never get a two you'll just get a one forever so randint actually does include it what i should like learn my python right i don't understand it so again these are one of those things i'm glad these these things get caught on camera and i won't edit them out because this is so common right they asked einstein how many feet are in a mile and he goes i don't know and he says i don't care because i don't want to use my brain to memorize a bunch of irrelevant facts i want to use it to think so here i don't want to just memorize everything usually what programmers do is even programmers who program every day you know and we do it as a job will if all almost always go and look it up some documentation just to make sure that what they're doing they're doing it correctly okay so these things not everybody has them memorized so that's why you refer to the documentation and just double check so anyways this will guess a number from one to six including one and six then it gets printed out if that number that was guessed was five then it goes you lose and it breaks out of the loop and everything stops if this uh and then after all of that it just increments count by one okay so if obviously this if condition hasn't run if count ever gets incremented by one obviously the if condition hasn't run because if it had the loop would have been over and you would have never gotten to line 14. then it goes again generates a number if it was not five then it increments count by one if it was not five again it'll increment count by one eventually when count is first time count is zero then it's one then it's two and if it hasn't met this if condition and uh it hasn't evaluated to true for the first three times of the loop then you this part evaluates to a false and you get to the else part of the loop and it says you went okay so let's go back and just run it so we made sure we understood it then just run it and go okay all right we're done your own while else so now we write our own now you should be able to make a game similar to the one in the last exercise the code from the last exercise is below so you guess guess guess if you don't guess correctly you lose eventually after a certain number of times uh and you do guess is equal to intra input which means that i take your input and i convert it to a string right so here right instead if i did int it won't actually show you but if i do let's say user is equal to this and i say five and i do type of user so what type of what was the type of the answer and if i just print that user it'll show you that it's five and it says the type is int but if i don't wrap it in integer function then what it shows you effectively is uh if i do user it shows you that it's a string five right and if i do type of user and it's a string type not an type which is why you need to wrap it into an integer function remember raw input turns user input into a string we use int to make it a number again okay so that's essentially what's going on there use a while loop to get the user to let the user keep guessing so long as guess is left is greater than zero so while is greater than zero keep running which means that we're probably going to be decrementing it every single time right just to think about it if guess is left is three next time guess is left is two then it's one then it's zero meet some kind of condition and then loop should stop ask the user for their guess just like the example above if they guessed correctly print break let's start coding this up so we're going to say while guesses left is greater than zero and i'm just gonna write this part right here for now left minus equal one sometimes i just write this part right away so i know my loop will stop at some point because i do know i want to make it stop and i don't want an infinite loop so i write my breaking condition right away and then i'll like most of the times write my code in between that so i'll write my code for example now here because i know i'm safe and my loop will stop okay so use a all right ask the user for their guess i'll say guess is equal to ant raw input and i will say please enter your guess this little space is nice so user can type when the user is about to type their cursor is blinking where my cursor is right now but if i didn't have the space their cursor would be where my cursor is right now that would look weird i also put the colon here because sometimes people will do this and it's weird when it says please enter your guess end of sentence and you're typing right there it's a little confusing so colon makes more sense it's a better user interface two parentheses to close off the right input function parentheses and then the second parenthesis to close off the integer int function parentheses okay if they guess correctly print you in okay so if guess is equal equal to uh the random number that was generated then print you win okay and then break out of the loop okay else print you lose okay so this part what happens it keeps running and then once the the wild condition evaluates to once the wild condition evaluates stuff falls it prints out this part let's step through the code line by line guess is this so the user gets to type in something once that user types in something it goes hey let me see if your guests match the random number that i picked from 1 to 10 inclusive so let's say the random number was 5. so it goes let's see if you put in 3 is that equal to 5 nope so it does not break out of the loop and it also does not say you win so we keep going you get to guess again and it decrements guesses left by one so guesses left initially was three then the next time will be two it goes here asks for the user input you put in a guess it checks if your guess was equal to the random number which again was probably five right we're not changing random number every time we picked it to be five initially and it stays as five the entire time the only thing is changing is guesses now let's say you guessed four so this part evaluates to false so it does not run the that block here goes to line 13. decrements guess is left by one so now guess is left uh goes from two to one eventually when guess is left is zero zero is not strictly greater than zero that evaluates to a false which means we go to the else part and uh you know none of this block of code runs we go to the else part and it just says you lose okay so that is it for that let's check it out uh please enter your guess we'll say three oh look at that i guess correctly the first time so the random number was actually three i had a one out of ten chance or sorry one two three one two three yeah yeah i'm not gonna count it i do know it's actually ten so i had a one out of ten chance to guess it right and i did all right now for loops so we just ended the section on while loops that's great so i think a perfect thing to do here is actually just end this video because we've completed a while loop section this way you get to practice some while loops in the comments below you can also put some while loops that you have made like actually put them down there and i'll comment and i'll tell you if they're wrong or if they're right or if they're cool and they'll also give other people an idea of what to do okay that way you guys can collaborate right here and if you um yeah so we're gonna continue from the next one so this is it this is qazi from cleverprogrammer.com if you enjoyed the video please give it a thumbs up subscribe make sure to subscribe so you can keep getting these amazing videos other than that i will see you in the next video codecademy python tutorial number 22. whoosh\n"