The Python while loop uses a conditional expression to control the execution of a block of code. This lesson demonstrates how the while loop works.
- [Male Voice] Python's while loop uses a conditional expression to control its loop. Here in Komodo I've opened a working copy of while.py from chapter six of the exercise files. You see, here's our while loop down on line seven and the condition, the conditional expression, is while this pw variable is not equal to the value of the secret variable. And the body of the loop is this one line of code which assigns the pw variable from the input function which inputs a line of text with a prompt.
And so the secret variable is set to a string that say swordfish in all lowercase, and the pw variable is set to the empty string. And so when I save this and run it, it asks me what's the secret word and I can put my cursor down here and I can type something in. And when I press return you see it asks me for the secret word again because the secret word was not correct. And if I type something else in, it's still not correct.
Try secret. Still not. Oh I'll type swordfish. And now the loop end because the conditional expression is no longer true. Password is equal to secret when I type in swordfish. And that ends the loop. So obviously you can use any conditional expression here. You just need to make sure that whatever it is you're doing in the loop will eventually resolve that and make that conditional expression no longer true. Otherwise you'll end up with an endless loop.
So the while loop uses a conditional expression to control the loop. It is simple and elegant and you'll see many examples of it throughout this course. And I'll show you some additional ways to control the loop later in this chapter.
- Python anatomy
- Types and values
- Conditionals and operators
- Building loops
- Defining functions
- Python data structures: lists, tuples, sets, and more
- Creating classes
- Handling exceptions
- Working with strings
- File input/output (I/O)
- Creating modules
- Integrating a database with Python db-api
Skill Level Intermediate
Python: Programming Efficientlywith Michele Vallisneri2h 15m Intermediate
Learning Python Web Penetration Testingwith Christian Martorella2h 49m Intermediate
2. Language Overview
3. Types and Values
8. Structured Data
11. String Objects
12. File I/O
13. Built-in Functions
- Mark as unwatched
- Mark all as unwatched
Are you sure you want to mark all the videos in this course as unwatched?
This will not affect your course history, your reports, or your certificates of completion for this course.Cancel
Take notes with your new membership!
Type in the entry box, then click Enter to save your note.
1:30Press on any video thumbnail to jump immediately to the timecode shown.
Notes are saved with you account but can also be exported as plain text, MS Word, PDF, Google Doc, or Evernote.