Python Fundamentals Code Sample
Transcript from the "Code Sample" Lesson
>> Nina Zakharenko: Let's quickly take a look at the anatomy of a Python program. Let me open that in VS Code. You're not necessarily gonna understand this code right now and that's fine. This is what we're going to build towards in our final exercise, so just quickly take you through it.
[00:00:19] We're gonna use the GitHub search API to search for popular repositories based on the language that they're written in, and the number of stars. So, this is a method called createQuery that helps us build the query string that we're gonna pass into the GitHub search API.
>> Nina Zakharenko: And let's start from the bottom here.
[00:01:12] And let's look at this repos_with_most_stars. The nice thing about VS Code and the Python extension is if you mouse over this method, repos_with_most_stars, and you Ctrl+click on it, it'll take you right there. So this repos_with_most_stars method, it takes a list of languages. It takes a default sort, for this program it's gonna be stars.
[00:01:42] And then it takes the order that it's gonna sort in, which is descending. We're gonna create our query, the create_query method we saw above. We're gonna define some parameters that we want to be part of our URL. And then we're gonna pass in the query and the parameters as part of a request, using the request library.
[00:02:03] We're gonna get back a response that has a status code. And we're gonna do a little bit of checking here. So, we're using the unauthenticated GitHub search endpoint here. If the status code was not 200, that means some type of error occurred, so we're gonna raise an exception and quit our program.
[00:02:26] Otherwise, we're going to get the JSON from the response. We're going to get the items key from that JSON, and then we're gonna return all of our records.
>> Nina Zakharenko: So pretty exciting, right? I'm gonna quickly run this program, and I don't assume any of you to have it open, we'll get there.
[00:02:49] So in VS Code, if I want to run the program, I'd open my command palette, Cmd + Shift + P or Ctrl + Shift+ P. Type Python to narrow it down, and then I'll just select Run Python File in Terminal,
>> Nina Zakharenko: And here we go, here's my results.
[00:03:32] A Python repo here, awesome Python, and a few other things. Pretty cool, right? Quick and easy.