Python Jumpstart by Building 10 Apps Transcripts
Chapter: App 5: Real-time weather client
Lecture: Multiple values from a function
0:00 Well, here we are. We've got our city,
0:01 state, and country, but our function over here,
0:04 it just returns one thing: a
0:07 string. Or something else, a number or whatever. Functions just return
0:11 one thing, actually, sorry,
0:12 this one, but same idea: returns one thing.
0:16 How can we take all that data that we've gathered, the city,
0:18 state, and country and return them back?
0:20 Well, what we can do is we can create something called a tuple.
0:23 So a tuple, we'll call this "loc" for a minute,
0:27 the way we create this in Python,
0:28 we would just say "separate things by commas",
0:32 and then we could actually return that one thing like this.
0:35 Let's see what we get if we do this.
0:37 We say Portland, Oregon, USA.
0:40 Look what the location is. It looks a little bit like a list,
0:43 but it has parentheses instead of square brackets,
0:45 which means you can.. it means it's a tuple.
0:48 but the limitations are you can read the values of it,
0:51 but you can't add to it and stuff.
0:52 But other than that, you can kind of think of it as like a list
0:55 a little bit. So this is cool.
0:57 And then up here, we have to say we get our one location,
1:01 but what we really want is the city,
1:03 state and country. So on the other hand,
1:06 on the reverse side, once I have a tuple,
1:08 I have this really cool thing
1:09 that I can do in Python, It's called tuple unpacking. So I can say
1:12 "city, state, country equals location".
1:16 And then let's just print out these things here,
1:19 see what we got. If We come over here in Portland,
1:24 Oregon, USA, look what we get when
1:26 we print this out right there.
1:27 That's those three things just with a space between them,
1:30 that's how print works if you just put multiple things into it.
1:33 But they all came back into city,
1:35 state and country. We could even put a break point right here, at the debug,
1:40 and notice city is Portland, state is Oregon,
1:42 Country is USA, perfect. Now, We don't need these intermediate steps,
1:46 Actually. I just wrote them
1:48 so it's really clear what was going on.
1:50 So what I want to do is I just want to say for the moment,
1:53 city, state, country equals that, and the tuple unpacking will just happen automatically,
1:58 and then down here we created the location and we returned it.
2:01 We can also just do you like that.
2:04 We don't need this anymore, okay?
2:06 So one more time. Here we go.
2:10 We got them back exactly as we had hoped.
2:12 So how do we return multiple values from here?
2:15 We just return a tuple.