Easy-to-follow video tutorials help you learn software, creative, and business skills.Become a member
If statements in Python can be extended to test multiple conditions using elif. Let's go ahead and make a working copy of conditionals.py, call it conditionals-working.py, and we'll go ahead and open our working copy and define a variable here. We'll say if v is == to one, print v is one elif v == two, print v is two, and we could do as many of these as we wanted to.
So, when we save this and run it, you'll notice we get v is one. And if we change this one to, say, a three, save that and run it, then we get v is three, but if we make this a seven, then save that and run it, nothing at all happens. Now, if you want to have a default case, you can simply say, else: and this still gets executed if none of the conditions turn out to be true. Say, print v is some other thing, and save that and run it, and we get V is some other thing, because v is seven.
So, the thing to understand about this is that only one of these suites is ever going to be executed. So, you have if, and an expression that evaluates to true or false, and a colon, and a suite, and then with each of the elifs, you also have an expression that evaluates to true or false, and a colon, and a suite. Only one of these suites is ever going to get executed, and that's the purpose of elif. It allows you to have several different conditions that get evaluated, and only one of them will ever get executed.
And then finally, the else clause is executed in the event that none of the conditions is true, but again, only one of these suites will ever be executed.
Get unlimited access to all courses for just $25/month.Become a member
82 Video lessons · 97355 Viewers
61 Video lessons · 84610 Viewers
71 Video lessons · 68810 Viewers
56 Video lessons · 101280 Viewers
Access exercise files from a button right under the course name.
Search within course videos and transcripts, and jump right to the results.
Remove icons showing you already watched videos if you want to start over.
Make the video wide, narrow, full-screen, or pop the player out of the page into its own window.
Click on text in the transcript to jump to that spot in the video. As the video plays, the relevant spot in the transcript will be highlighted.
Your file was successfully uploaded.