Easy-to-follow video tutorials help you learn software, creative, and business skills.Become a member
Some languages have a special control structure, called switch, or case, or something like that, that allows you to select from multiple choices of a single variable. Python doesn't have one. So, we're going to take a look at one particular strategy where you can do this very easily within Python, and you'll see that it's not necessarily a weakness in the language; it's just different way of looking at things. So, we'll go ahead and make a working copy of switch.py, call it switch-working.
We'll open our working copy, and we'll start by declaring a dictionary. We'll call it choices, and we'll just put in a few choices here, one first, two second, three, and we'll declare a variable and then we'll select based on that variable.
So, when I save this and run it, you'll see that we have selected one and we printed out first. And if I change this to say three, save that and run it, it'll save third. So, here we've been able to very easily select based on a number of choices, and we could make this a very long list if we wanted to, and we can add things, delete things from the list, and change things in the list, and this will all work exactly as expected. The one thing this does not do well is if I select something that's not in the list, you'll see that we get an error, save that and run it.
Of course, we can trap this error with try and accept, or there is an even easier way to do this. We can use the get method of the dictionary object, so you get V comma, and then I can put in a default result, and I can say other. And so what that does is it looks for V in the dictionary, and if it doesn't find it, it gives you back this value. So, if I save that and run it, you can see we get other, because we have seven. If I put in five, then I'll get fifth. Save and run and there is fifth.
So, this is a very simple way to do what most people use switch statements for and you'll see some other examples, including an example of executing code based on multiple choices, later on in the course.
Get unlimited access to all courses for just $25/month.Become a member
82 Video lessons · 101773 Viewers
61 Video lessons · 88535 Viewers
71 Video lessons · 72348 Viewers
56 Video lessons · 104059 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.