Locked learning resources

Join us and get access to thousands of tutorials and a community of expert Pythonistas.

Unlock This Lesson

Locked learning resources

This lesson is for members only. Join us and get access to thousands of tutorials and a community of expert Pythonistas.

Unlock This Lesson

Dealing With Multiple Values

00:00 In the previous lesson I showed you how to catch exceptions to handle conversion errors. In this lesson, I’ll show you how to do simple parsing of a user’s response to divide it into multiple values.

00:11 When you’re looking for multiple values from the user, there are a couple of ways to approach the problem. One would be to just call input() multiple times,

00:19 but if the number of things you’re looking for is variable, then that doesn’t work. Instead, you could put your input() call in a loop and then count the number of responses, or have a key response like the word done to trigger the end of the input loop.

00:35 Both of these are kind of clunky though. If you’re counting, you have the same problem as the static number of inputs, and if you’re triggering something like done, that means you can’t actually collect the word done.

00:46 A more common approach to allow the user to type multiple things is let them use a single response, then parse that response into multiple values.

00:55 One way of distinguishing multiple values is to separate them with a character like a comma. With that, you can use strings .split() method to chop a string up into pieces based on that character.

01:07 This code demonstrates a string called colors containing comma-separated values. Calling the .split() method returns a list containing the substrings that were separated by commas.

01:18 Note that because I wrote comma space, the green and yellow items are actually " green" and " yellow".

01:25 I’ll show you a quick way to deal with that in the program that I’ve written next.

01:30 This is a script called quiz.py. It’s the world’s shortest trivia program. It asks exactly one question. Here, I’m storing the correct answer to the trivia question as a set data type.

01:43 If you haven’t seen these before, they’re a container kind of like a list, except the order doesn’t matter. This is useful for our case as the question has four things in the answer, and I’d like the user to be correct no matter what order they type them in.

01:57 There are a couple of ways to construct a set. Here, I’m using the set() constructor, passing in a list containing the four parts of my correct answer.

02:06 The constructor will read those items and store it unordered in the set. Alternatively, you can just use brace brackets as a shortcut, but if you’re new to sets, this explicit way is a little clearer in the code.

02:19 Here, I’m printing out our trivia question to the screen: What are the four colors of the Kenyan flag? And hopefully this is familiar. This is where I call input() to get the user’s response.

02:30 The response variable will contain a string. I need to carve that up into pieces and create a new set containing those pieces. I can then compare the user’s answer with the correct answer above to see if they’re right. On this line, I’m creating an empty set, which I’m going to stick the user’s parsed answers into.

02:49 You’ll recall that .split() returns a list, so this line of code loops over that list’s contents. The response variable got populated from input(), so it contains a string.

03:00 Strings are objects and they have methods, and this is that string’s .split() method. Using a comma as the argument here tells .split() to look for commas in the string being parsed, and to use that as the parsing delimiter.

03:13 Inside of the loop, I’m handling each parsed value. Ultimately, I want to add it to the user’s answer set. Along the way, I want to do some cleanup first.

03:22 word is the loop’s variable, so it gets populated with each thing the user typed in between commas. word is a string. Another handy method on a string is .strip().

03:34 The .strip() call returns a new string with any leading or trailing whitespace removed,

03:40 remember " green" and " yellow"? Well, this fixes that problem.

03:44 Since .strip() returns a string, I can chain another string method on its response. The .lower() method returns a new string with all the characters converted to lowercase.

03:54 String comparisons are case sensitive by default, and since I’ve used all lowercase in my correct answer set, this ensures that a user capitalizing an answer won’t be told they’re wrong.

04:06 So to recap, response contains a string with comma-separated values. .split() chunks it up based on commas. If it turns out there aren’t any commas, you still get a list back with just the original content, so line eight will work either way.

04:21 Line eight iterates over those split values, putting each of them into the word variable. Then on line nine, I remove leading and trailing whitespace with .strip(), and then turn the result into a lowercase string.

04:34 The cleaned value then gets used as an argument to the .add() method of the answer set, storing it away. Once I’ve got the user’s response stored away in a set, I can then compare it to the correct answer.

04:47 You can compare two sets with ==, and since sets don’t care about order, as long as the user has typed in our four colors, they’ll get a message saying that they got the answer correct.

04:58 If the user didn’t type four things separated by commas, or they didn’t type the right four colors, then the else block runs, and they get an error message.

05:07 Inside of this print(), I’m using the .join() method. It’s also a method on a string. Python’s a little funky here. String literals are themselves objects, so you can call string methods directly on them.

05:19 Here the string is ", ", which I then call the .join() method upon. .join() takes an iterable, like a list or a set, combining each item in the iterable together based on the string object.

05:33 So in this case, I’ll get a string containing a comma-separated list based on the correct answer, which I then use in the error message to tell the user what they did wrong.

05:43 Let’s try this out. There’s my prompt

05:52 and there’s my answer, and as soon as I hit Enter, I get told I’m correct. Note how my weird mixing of cases and extra spaces got handled properly. .strip() and .lower() made sure that the comparison was correct.

06:07 One downfall of this approach is what happens if the user doesn’t follow instructions. If I had typed "red white green black", since the string has no commas, it would be considered a single thing.

06:20 Although the user was technically correct, their lack of ability to follow instructions means the comparison will fail because their answer set will only contain a single string.

06:28 There weren’t any commas to split upon. On one hand, it’s sort of like in Jeopardy when the contestants forget to answer in the form of a question. On the other, this isn’t the most user-friendly approach.

06:40 There are ways of splitting on sets of characters, but it requires a regular expression, which is way beyond the scope of this course. That’s something else you might want to add to your to-do list if you like, but it’s a more advanced topic, so maybe stick it further down your list.

06:56 A quiz with only a single question kind of sucks, so I leave it to you to judge whether having homework sucks more, or whether you want to fix it. Here are some ideas you might try if you want to play around with your program.

07:09 The first idea would be to add some more questions. One possible way of doing that is to store the question/ answer pairs in a dict, then loop over the dictionary’s contents.

07:19 Another idea would be to make the quiz a little friendlier by disallowing the wrong number of values in a response. So instead of telling the user they’re wrong if they only typed in three flag colors, treat that as invalid input and get them to type in four colors.

07:35 This combines the idea of the while True: loop you saw for invalid numbers in the previous lesson, but this time, you’d be counting the user’s split responses in order to allow them out of the input loop.

07:47 If you get the multi-question dictionary working, try adding lots of questions. Then use the random module to select a subset of those questions from the dictionary so the user gets different questions each time.

07:59 The sample() function in random takes an iterable of allowed values and a number of values to choose. The example here picks three numbers in the range from 0 to 9. You’ll need the length of your dictionary instead of the range() call, but hopefully you get the idea.

08:16 The input() function shows what the user types on the screen. Most of the time that’s what you want, but sometimes it isn’t. In the next lesson, I’ll show you how to hide the user’s input.

Become a Member to join the conversation.