# Python Jumpstart by Building 10 Apps Transcripts Chapter: App 9: Real Estate Analysis App Lecture: Concept: Python 3 AND Python 2

0:00 Let's take a moment and look at this core concept of one mechanism for supporting both Python 2 and Python 3.
0:07 You saw in our previous example that we wanted to use the statistics module to compute the mean, now I realize there are many ways to compute the mean,
0:15 we don't need to fall back on this, it's a pretty simple mechanism but the idea is there is some module or some feature
0:21 in a later version of Python that wasn't supported in a prior one. So this is not even about Python 2 versus Python 3,
0:29 this is like Python 3.4 versus previous versions, ok, so the statistics module is imported in Python 3.4.3
0:38 if we run this code on anything earlier than that, it's going to fail, it's going to say there is no module statistics, right,
0:45 if we have it it's a super easy way to compute the mean of a set of numbers, you can see below, we've got a bunch of numbers, static.mean numbers boom,
0:53 out comes the average. But it fails on a lot of the versions of Python. So what do we do?
0:59 One way we can solve this problem is we can use a try and just an empty except, there are possible problems you can expose yourself to here,
1:05 but in this simple case it definitely works well. So, we can say it look, let's try to import the statistics module,
1:11 if it doesn't work it's going to throw an exception and we could actually catch the right type of exception,
1:17 we'll get into exceptions later in the next app, but it's easy enough for us to go and write the statistics to stand_in.py
1:25 and we define a mean method and it takes the same parameters as the real one and the implementation you saw in the previous example write it,
1:32 it was quite easy. So the way we solve our problem and we get sort of code that runs on all the versions of Python is
1:39 we try to import the statistics on new versions that just works and uses the best new module for that if it doesn't work
1:45 it's going to fail fall into the except block and we are going to use this specific type of import say we are going to import statistics to stand_in
1:54 and we are going to actually give it the name statistics for this particular file and since it's a mean method,
1:59 the statistics.mean it works exactly as we would expect. Boom, now our code works on all the versions of Python, just like that.

Talk Python's Mastodon Michael Kennedy's Mastodon