1. Home
  2. Explore
  3. Computer Science
  4. CS50 Week 7: Data Tools

Study methods

Flashcards
Quiz
Fill in the blanks
Written test
Lesson
Notes
Podcast
Content

CS50 Week 7: Data Tools

Transcript

[MUSIC PLAYING]

SPEAKER 1: All right. This is CS50, and this is week 7 on the day before All Hallows' Eve. Today, we will introduce yet another language, the goal of which is not to introduce another language for language's sake, but to really begin to emphasize that when it comes to the world of software programming, engineering more generally, there's often different tools for different jobs. And if you were to try to use C to solve all of our future problems, it would actually be painful, as you've already seen how much more pleasant it is to solve certain problems with Python. But today, quite quickly, we'll realize that even Python's actually not the most pleasant way to solve a lot of problems, especially when it comes to data, data at scale. And, in fact, as we transition in the final weeks of CS50 to the world of web programming, and if you so choose with your final project mobile programming, you'll actually need more tools in your tool kit than C and Python alone.

In fact, today we'll introduce a database-centric language called S-Q-L, or SQL. Next week, we'll explore markup languages, like HTML and CSS. A bit of JavaScript, as well. And then we'll synthesize all of this together at the end of the class, as some of you might, for your final projects, as well. But, before we do that, and talk about data, let's actually start to gather some data. So if you could visit this URL here on your phone, or a laptop. Or, if easier, here's a bar code version thereof. You can point your camera at this bar code here, and it's going to pull up a relatively short Google form that's just going to ask you a couple of questions, so that we can collect some actual live data and actually play around with it, initially, in Python. So if you go to that URL there, you'll see a Google form. And if you haven't been able to scan it quite yet, that's fine. Just kind of look over the shoulder of the person next to you.

But you, or they, will see a little something like this. So among the questions will be, which is your favorite language? On the list, only thus far, is Scratch, C, and Python, and below that you'll see another question asking about your favorite problem across the problem sets thus far. Each of them is radio buttons, which means you'll be able to select one button for each of those questions. And, ultimately, what's going to be nice is that if you've never used Google Forms before as an administrator, all of that data is actually going to end up being, not only in Google Forms, but also, if you so choose, in Google Spreadsheets. Which is an example, of course, of a spreadsheet software similar in spirit to Apple Numbers on Macs or Microsoft Excel on different platforms. And Google Sheets is going to allow us to store all of that data in rows and columns. And so, since Google made both of these products,

they integrated one with the other. So, in fact, if I, on my laptop here in another window, open this up-- let me flip over. Here's the live spreadsheet. And we'll see that the very first person who buzzed in really liked Python, as did a lot of other people thereafter. But, Hello, World was your favorite in Python, which is great. There's a couple of votes for Scratch here. If we scroll down, there's one hold out for C, who really liked Credit, in this case here. And if we scroll down further, it looks like Python and Scratch are in there. A few more C's, and so on and so forth. So suppose that we wanted to, actually, now analyze this data. Now, any of you who have used Excel, or Numbers, or Google Spreadsheets know that it comes with built in functions and formulas, and we can do all of that, but suppose there was a huge amount of data. Or, suppose that this data was not coming in via Google Sheets,

but via your own web application, or your own mobile application, and it's just ending up in some kind of spreadsheet. Well, wouldn't it be nice if we could actually analyze that kind of data with code. And, in fact, you can. And the simplest way to store a bunch of data isn't with anything fancy, in fact, but just a literal text file, something ending in .txt, or, maybe more commonly, .csv. In fact, what we'd call a flat file database is literally just code for a text file containing all of your data. But your data typically has delimiters that separate some values from others. And, in fact, the most common approach, daresay, is to use, indeed, comma-separated values, or, CSV files. And what that means is that in simple text alone, just asking, maybe Unicode, you sort of mimic the idea of rows and columns by using newline characters, like backslash n, to represent row after row after row. That's pretty straightforward.

To just move the cursor to the next line. And because text files aren't graphical, so there's no notion of vertical bars that you can put between what you and I think of as columns, you literally just use a comma, or some other such symbol to separate one value from another. So, in fact, let me go ahead and do this. Even if you've never done this before, it turns out, in Google Sheets, and also Excel and Numbers, you can export your data, not in some proprietary Apple or Microsoft or Google format, but in a globally portable format known as .csv. So let me go up to file. I will go to download. And notice, I can export this in a bunch of different formats, but the one I care about for today is going to be .csv. On my Mac, that's going to put it into my downloads folder. And what I'm going to go ahead here and do, in just a moment, is let me go ahead it and open up VS Code. So, in short, I've downloaded this file.

Google gave it a long default file name. I've renamed it to favorites.csv. Let me go ahead and actually open it now in VS Code here. And this now is the exact same data. If you're still submitting the form, I'm afraid you didn't make the cut off. So we're not going to see more data ending up in this file because I've literally downloaded a copy of it. But, indeed, if I scroll through this, we'll see that it's got some 399 lines of data. Or, technically, 398 because the very first one is what we'd call a header row, which just describes what each of these columns means. Now notice that even though the Google Sheets interface actually put all of this data in proper graphical rows and columns, you can still see the rows because they're just separate lines, and you can kind of see the columns by focusing on the comma here, the comma here, the comma here. And then, also, the comma here, the comma here, the comma here, and so forth. Now, a quick subtlety.

Hello, World is a two-word problem name, and it itself has a comma in it. What's to stop me from confusing the comma in Hello, World from the commas that Google, apparently, inserted into this file? Yeah. So, automatically, you all did not type this. We did not type it into the form. But Google is smart enough, as is Apple and Microsoft, when they export CSVs to somehow escape seemingly dangerous characters, or characters that could just break things. And, in this case, a convention in the CSV world is just to quote any strings that themselves have commas so that any program you're writing that reads this file doesn't get confused. So the only thing that came in automatically from Google is just this timestamp here, based on the time of day in our own local timezone. That was added automatically. So we have three, and not just two columns. So with that said, we have three columns: timestamp, language, and problem.

The latter two of which came from all of you. Let's actually write some code that analyzes this data. Let's figure out what the most popular something or other is here. So I'll close the CSV file. Let me go ahead and use what seems to be folks favorite language, thus far, and write a file called favorites.py, for instance. And I'm going to use Python to open that CSV file, analyze it, crunch some numbers, and output some statistics, if you will. So the easiest way to manipulate CSV files, as you might have gleaned, is not to just open the file yourself, look for commas, allocate memory, or anything like that in C. In Python, you can literally just import CSV, which is a Python module that gives you CSV related functionality. In Python, there's a bunch of ways to open files. One way to open a file is like this in Python. You can say file equals open, similar to fopen in C.

You can specify the name of the file you want to open, like favorites.csv, and you can explicitly say you want to open the file for reading, quote unquote, "r," just like fopen. Strictly speaking, in Python read is implied. So if you omit the second argument, it will still work. But for parity with fopen, I'll do the same here. Then you can, maybe, do something with file, and then, at the end, you can close the file like this. So in Python, there really is a mapping between fopen and fclose. But in Python the functions are called open and close for short. But a more common way, a more Pythonic way, so to speak, i.e. the way people tend to do it in Python, is actually to use a keyword that didn't exist in C, where you instead say with. And you say, with open this file name as a specific file name, and then indent it inside of that. Now you can do whatever you want with the file. And the implication of using with, even though it's not

obvious from the keyword itself, is that the file will be automatically closed for you later. So this is just a minor Python convenience so that you don't have to remember to close the file. Unless something goes wrong, it will just close automatically as soon as you're outside of this with block. So how do I go about reading a CSV? The simplest way is to actually give yourself a variable called, maybe reader. Like if I want to read the CSV, I'll call my variable reader. Set that equal to the return value of a function that comes with Python CSV module called reader, in lowercase, and you just pass in the file name. So the first line there on line three opens the file and gives me access to the bytes there in. Line four now actually uses this library that comes with Python to just go read it for me, figure out where the commas are, so that it can hand me, line after line, the data in the file. Now the first piece of data in the file, though, was what?

What's the very first row? So it was that header row with timestamp, language, problem. I actually want to skip that because that's not data. That's what we might call metadata that's describing my actual data. So one way to deal with this, I can literally just say next reader. And next, even though the semantics here are a little weird, it just means, no, no, give me the next line from that reader instead of the first by default. And now inside of this with block, I can do something like this. For each row in that reader, let's do something super simple initially. Let's just print out row bracket one. So row bracket one. So what's going on here? Well, the CSV reader in Python is going to return to you, inside of this loop, one row after another. Each of those rows, though, has how many columns? Three. The timestamp, the language, and the problem. And just like in C, our lists in Python are zero index. So zero, one, two.

So if I'm printing out row bracket one, that's the second, or middle, column. So what's this going to print row after row? Each of the languages that you all replied with. So that's all. This isn't doing any kind of analytics yet. I'm just going through the motions to, at least, print out some data of interest. So let me run this. Python of favorites.py, enter. And it happens super fast. But if I scroll back in my terminal window, there is all of that raw data. So this is to say, once you know the function names, once you know the keywords, it's actually pretty simple in Python to just get up and running with a file, and start looking at the data therein. But it turns out that it's a little sub-optimal to use the reader alone. It turns out there's better ways to do this, and let me make this clear as follows. I don't strictly need a variable, but let me actually declare a variable called favorite, set it equal to row bracket one,

and then print out that favorite value. This is not doing anything new. It's just declaring an additional variable, but I wanted to highlight the fact that I'm just kind of trusting that row bracket one is the problem-- or, is the language I care about. Is language, is language. But suppose one of you, or I, go into the Google spreadsheet, and like anyone might with a spreadsheet, you might start moving things around. And you might swap some of the columns left and right. You might delete one of the columns, add something else. In short, spreadsheets are arguably fragile in that it's pretty easy in the GUI, the graphical user interface, to change them around. And so my code in Python, accordingly, is, arguably, fragile because I'm just hoping that row bracket one is always the data that I care about. So what would be marginally better? Well, let's actually use that header row instead. And more common, arguably, in Python, is not to use a simple reader,

but, instead, what we would call a Dictionary Reader. I'm going to change this to DictReader, capital D, capital R, and that's it for the change to line four. On line five, I'm going to get rid of the next line because I don't want to skip the header now. What DictReader does, which reader does not, is it automatically analyzes that first line in the file, figures out what are all of your columns called, and, thereafter, when you iterate over this reader what each of your rows now is-- it's no longer a list of size three, bracket zero, bracket one, bracket two. Each row that you get back in this loop on line five is now, wonderfully, a dictionary instead, the keys of which are from the header field. Timestamp language problem. The values of which are whatever each of you typed in again and again. So how do I change the code? I no longer have these numeric indices because row is no longer a list, it's a dictionary. So if I literally want the language that you typed in,

I can use row bracket, quote unquote, "language," treating row as a Dict not as a list anymore. Now this is, again, more robust because if you move the columns around on me, code is still going to work, at least so long as you don't rename the columns at the very top. So that's still one assumption I'm making. All right. Well, beyond that, what could I actually do here? Well, just to be clear, I don't, strictly speaking, need this variable. So no need to highlight this again. So let me just simplify the code a little bit and get rid of this variable, and instead just print out the language in that row. As a quick check, let me rerun Python of favorites.py and it seems to still work, even though there's a lot of output. We're not going to check all 399 lines, but it looks like it printed out all of those popular languages. Well, what more can we actually do? Well, let's actually now start to crunch some numbers

and figure out how many people like Scratch, how many people like C, how many people like Python. Let's start to analyze this. So maybe the most pedantic way to do this in Python would be to just create some variables and do all of the counting myself. So let me actually go ahead and do this. Let me delete this code for now. And after opening the reader, let me create a variable called Scratch and set it equal to zero, a variable called C, set it equal to zero, a variable called Python, set it equal to zero, just so that I have three counters, similar to what we did in week zero, week one, anytime we counted anything Honestly, this looks a little stupid, and it's not wrong. In fact, this is how you would do it in Python, but Python also has some clever syntax. If you want to be really cool, you can do Scratch comma, c comma, Python equals zero, zero, zero, and do all three at once if you like that. So it tightens up the code a little bit, even though the effect is ultimately

the same. Now let's go ahead and iterate over this file row by row by row. And if we see Scratch, increment the Scratch counter. If we see C, increment the C counter. If we see Python, increment the Python counter, instead. So how do I do this? Well, I could do something like, for each row in the reader, just like before, let me go ahead and get that favorite variable and set it equal to the language in that dictionary that just came back as part of this iteration. And now I can do something like this, if favorite equals, equals "Scratch" then, with my indentation, I can do Scratch plus equals one, elif favorite equals, equals "C." I can go ahead and increment C plus equals one. Else-- and I don't think I want else, just to be safe. Even though we only saw three options, I think just to be super safe, elif favorite equals, equals "Python," then let's go ahead and increment Python. The one thing we can't do that we could do in C is the plus, plus trick.

So plus equals is as close as we can get. So what have I done? Inside of this loop, I've just incremented each of those counters by one if I see Scratch, or C, or Python, again and again. All right. Outside of the loop and outside of the with block, because once I'm done reading all of the rows, I might as well let the with clause close the file automatically, let's just go ahead and print out some values. So I'm going to go ahead and print out Scratch colon, and then inside of there let's print out whatever the value of that variable is. Let's then go ahead and print out C colon, and then whatever the value of the C variable is. And then, lastly, let's print out Python colon and whatever the value is. And now I made three typos here. This is not going to print the values. What do I need to do? Sorry? Yeah, I'm missing the f in front of each of these strings so that I actually get formatted. And that is to say, the variables get interpolated inside of the curly braces

like we saw last week. All right. So, honestly, that's kind of a decent amount of code, like 18 or so lines of code, just to count the number of responses. But let's see if I got it right. Let me open my terminal and run Python of favorites.py, and now I see, by an overwhelming amount, folks like Python, followed by C, followed by Scratch, in that order. But that was a decent amount of code to have to write, and it turns out there's actually better ways of doing this, more Pythonic ways, more programmatic ways of doing this. And if we think back to one of our universal data structures. Think back to how we preached last week, and the week before, the value of these dictionaries, more generally. Like the CSV module, clearly a fan of them, because that's what DictReader is giving us, dictionary, after dictionary, after dictionary. And this was the general idea of a dictionary. It associates keys with values, much like you might in a two-column table on a chalkboard, or the like.

Well, this is what I need if I want to keep track of how many people said Scratch, and C, and Python. If I had a piece of chalk, I could just write Scratch, and C, and Python as three keys. And then with my chalk and, maybe, an eraser, keep track of the values. They all start at zero. Then, I add one, add two, add three. Or, maybe, on a chalkboard, I actually use hash marks. But a dictionary is kind of the perfect data structure for just associating something like Scratch, C, Python, with something else-- keys with values, respectively. So this is going to look a little weirder, but it's going to be pretty conventional to do something like this instead. Let me go back into VS Code. I'll close my terminal window. And let me go ahead and actually delete a lot of this because I can simplify this further. Let me go ahead and now give myself, maybe, a variable just, generically, called counts, and set that equal to an empty dictionary.

And you can actually do this in a couple of ways. You can literally write out dict with nothing in parentheses, which will give you an empty dictionary, like the picture on the board, but a little more conventional is to just use two keystrokes and use two curly braces with nothing inside. That gives me an empty dictionary like this picture here. Now my loop is going to be the same. I'm going to do, for each row in the reader, I'm going to go ahead and grab the favorite language for this person. So favorite equals row, quote unquote, "language." But now I'm going to do something a little different. There's two scenarios here. Either, I have seen this language before and I want to increment it by one. Or, if I've never seen this language before because the loop just started, what should I initialize the count for this language to? So, one because I've only seen it once. Exactly. So now let me go ahead and do exactly that. If this current favorite, that I am seeing in the row,

is already in the counts dictionary-- and in Python, this is literally how you ask that question. If favorite in counts. That will check, is there a key with this name, Scratch, C, or Python? If so, go into that location in the counts dictionary, index into it at the favorite location, because favorite is a string. It's either, quote unquote, "Scratch," "C," or "Python," and just increment it by one like this. Else, as you noted. If it's not there implicitly, then counts bracket favorite should probably be set equal-- not to zero because we're literally are seeing it in the current row. Let's initialize it to one. And, thereafter, if we see it again, it's going to be plus equals one, plus equals one, plus equals one. So now outside of that loop, outside of the with block, let me do this. For each favorite in those counts-- And this, too, in Python is a trick if you want to iterate over all of the keys in a dictionary.

That is, if you want to iterate over the left-hand column of all of these keys, you literally can say, for something in that dictionary. So for favorite in counts, this is giving me a variable called favorite and updating it automatically top to bottom in that dictionary. Let's go ahead and print out an f string that's going to say whatever the name of that language is colon, and whatever the value of that language is in that there dictionary. So, again, logically the only thing that's new is this. I'm now using one dictionary instead of three variables to keep track of three things, like updating this chalkboard with three different things, Scratch, C, Python. And the last thing I'm doing, which is a little different, is once I have that dictionary, whether there's three languages, or, maybe, tomorrow there'll be fourth because we're going to introduce SQL today.

Well, this will iterate over all of those keys and print out the values. All right, so if I didn't do anything wrong, if I do Python of favorites.py and hit enter. There we have it. And it happens to be in a different order this time. That's because we saw Python first, we then saw Scratch, and, eventually, we saw C. But if we wanted to sort these differently, we actually could with some different code. But, in short, what have we done? We've created this kind of structure in memory with three keys, Python, C, and Scratch, because each time we encounter such a language from you all, we either set our counter to one or increment it by one instead. Any questions on this code, or this general idea of using dictionaries as, like, a little cheat sheet for doing some math in this way? Super common paradigm. All right. Well, let me tweak this a little bit. Right now, in my output, we're seeing Python, Scratch and C.

Maybe, for the sake of discussion, suppose we want to sort this by key. We can actually do that. Let me close my terminal temporarily. And it turns out, in Python, there's a bunch of ways to do this, but the simplest way to sort a dictionary by key is literally to use a function called sorted that comes with Python, that just does it for you. And even if you pass it a dictionary, it will sort that dictionary by the left-hand column so you can iterate it over alphabetically instead. So if I go back now to VS Code. If I open my terminal window and I rerun Python on favorites.py, now that I've added the sorted call, we should now see just because it's sorted alphabetically instead. Now that's not that useful, especially if we had lots of languages. You probably don't care about it being alphabetized as much as you care about it being ranked by which is the most popular, which is the least popular. And, for that, there's a bunch of ways to do this in Python.

And, I think, the simplest way to sort by value the right-hand column instead of the left-hand column is probably to make this change instead. Let me close my terminal temporarily. Let me still use the sorted function, which by default sorts by key, but let's change it to be as follows. Let's change it to sort by a function called counts.get, which is a little weird, but this comes back to last week's brief discussion of object-oriented programming, or oop.

Remember, in Python, that almost everything is like an object of some sort. An int is an object, a dictionary is an object, a string is an object. Which is to say that, not only do these things have values like, quote unquote, "Hello, World," or 50, these variables, these objects, can also have functions built into them, a.k.a. methods. So it turns out that because counts is a dictionary, because I made it so, that counts dictionary, like any dictionary in Python, comes with a function called get. And if you just tell the sorted function to use that built-in method, it will actually, for every key, get its value, get its value, get its value, and sort effectively by the right-hand column instead of the left. Now we'll see down the line, perhaps, more sophisticated ways of using this, but, for now, this just overrides the default behavior and sorts the dictionary, not by key, but by value instead. All right.

So now watch this if I run Python of favorites.py once more. Previously, it was in the order in which the languages appeared first in the CSV file, then it was sorted alphabetically. Now it should be sorted by value. And indeed. Scratch is the least with 40, C is the next with 78, Python is the biggest with 280. That's not much of a top 10, or a top three list. Let's actually reverse it. And the easiest way in Python to do that is to pass a third argument into sorted, and you would know this by just reading the documentation. You can literally say, reverse equals True, capital T, and now if I rerun this one last time, Python of favorites.py, I'll see the same values but with the whole thing reversed in order. Long story short, even though this might feel like a slog, like adding this and looking up this, so much easier than in C where you would have had to figure out, how does bubble sort work? Let me implement bubble sort, selection sort, any of those sorting algorithms,

or use some other library. In Python, you just get a lot more for free, so to speak. It's just built in once you get comfy with the documentation. And, to be clear, this is an argument, as is this, as is this. But in Python, we have not only positional arguments, which are based on what position they are in, left to right, just like C, you also have these named parameters whereby they have explicit names that you can use yourself, to make clear that you're using this one but not this other one. More parameters in Python can be optional than in C. Phew. All right. Any questions about that technique yet? And if you're feeling like this is starting to take the fun out of Python, that's actually kind of the point of doing this the hard way. All right. Well, let's do it one other way that's marginally better. It turns out, in Python there really is this rich ecosystem of libraries, the code that comes with the language itself, or, even, third parties.

And coming with the language is another module called the collections module, or package here, whereby if I use from collections, I can import something called Counter, capital C. And it turns out, if this felt a little bit painful to create a dictionary yourself, initialize it, maybe, to zero or one, like this. Turns out, you have the same problem that people before you have had, and so there's another way to do this. You can create a variable called counts, set it equal to Counter, capital C, open paren, close paren. And this is a different type of object. It's a different type of object in Python, that has counting capabilities built in. And so if I actually want to use this counter instead, I can do this. For each row in the reader, let's go ahead and grab the favorite language from that row, just like before. And without doing any of that headache of like, if, elif, or any of this, you can literally just index into that counter using favorite,

quote unquote, "Scratch," or "C," or "Python," and increment it by one. What the Counter class is going to do for you, so to speak-- Another example of object-oriented programming, and counts is now an object thereof. What this whole feature of Counter is going to do for you is it's going to automatically initialize everything to zero, even if you've never seen it before, and then you can just blindly start incrementing it. So, in short, there's just more pleasant ways, sometimes, to do something in Python as well. All right. How about, lastly, let's make things, maybe-- Oh, actually, let's do this. We can even simplify the sorting here. Let me actually take this one step further. Instead of manually figuring out how to sort this, I'm going to do this. For each favorite, and the count thereof in the counts variable's most common function's return value, go ahead and print out this as well. So in short, again, a bit new syntax. But what's going on here?

Well, it turns out that this counts class and-- sorry, this Counter class, and, in turn, this counts variable, comes with a function built in that you would only know from the documentation. It's literally called most underscore common, and what it returns to you when you call it is a pair of key value, key value. And so this, too, is a trick in Python that we did not have in C. If you want to iterate over something, but grab two variables at a time on each iteration like this, you separate them by commas and can get favorite count, favorite count, favorite count. So if I run this now, Python of favorites.py, this, too, just works. And it's getting a little simpler, a little tighter than before than if we had actually done it all manually. Lastly, here is a code that's the shortest version thereof. We're down to like 14 or 15 lines. If I wanted to change this to analyze the most popular problem thus far in the class, how do I go about changing the code

to print out, top to bottom, the most popular problem or problems? What line should change? Yeah. So yeah. Line 10. Because I've written this in kind of a general purpose way and using dictionaries with keys, it suffices to change language to, quote unquote, "problem" because that was the third column from the CSV. And so now, if you're curious, let's actually make my terminal window a bit bigger. Python of favorites.py, enter. And OK. Tragically, we peaked early with Hello, World-- is the most popular problem thus far, followed by Filter, then Scratch. OK. Peaked even earlier. Mario, DNA, and so forth, and a bunch of others thereafter. So based on this sample size, here's the ranking of the problems thus far. So, we got it. More Hello, World problems in the weeks to come. All right. Now that we've done that in that way, let's just make this program slightly interactive and see how we can really take a fundamentally different approach. I'm going to go into VS Code.

I'm going to keep everything the same, except that, at the bottom, I'm going to get rid of this loop because I don't want any more print out everything. I want to look up specific counts. Like, how popular was this problem, how popular was this other problem? And what I'm going to go ahead and do is to create a variable called favorite, set it equal to-- I could use get string in the CS50 library, but we saw last week there's no need to for strings, certainly. Let me just use the input function that comes with Python, and prompt the human for their favorite problem. And then let me go ahead and print out, for instance, an f string containing whatever their favorite is, colon, and whatever the count is thereof of that favorite, close quote. So let me open my terminal window. Let me run Python of favorites.py, enter. And if I type in Hello, World, looks like 65 people, indeed, like that one. If I run Python of favorites.py again.

I type in Scratch, now we see that one. If I type in anything else, I'm going to get its specific value. So this is to say, not only can we write Python code to analyze some data pretty tightly versus the manual code we wrote out earlier, you can also make these programs interactive as well. And this is going to be a super common paradigm, right, if you go into the world of consulting, analytics, data science, more generally. Among your roles is going to be to analyze data, to ask questions of data, get back the answer. be ask questions of data, get back the answer. Honestly, life gets pretty tedious, even though you've only been programming in Python, perhaps, for like one week, a week and a half now. When you have to write code to solve all of the world's problems-- and there's this sort of tenant in programming, that programmers tend to avoid writing code as much as they can

because, ideally, you would solve problems with the right tool for the job, minimizing the number of lines of code you actually write. So how do we actually get to that point? Well, instead of just dealing with CSV files, pure text, it turns out there's an entire world of proper databases. Not flat file databases, where you store everything in text files, but a database program, a piece of software running on a computer, running on a server, that's always listening for you. It's got a lot of memory, it's got a lot of space, and in turn a lot of data, and it supports a database specific language that makes it much easier, much faster to ask questions of the very same data. It's a relational database in the sense, too, that it's not even necessarily one spreadsheet, one set of rows and columns. You can have two sheets, three sheets, 30 sheets across which there might very well be relationships, or relations. So S-Q-L, or SQL, is a database specific language,

stands for Structured Query Language, that's a declarative language whereby you're not going to be in the habit with SQL, typically, of writing loops and conditionals, and this kind of thing. You're instead going to describe the data that you want to get back, you're going to describe the question that you want the answer to, and we'll do this using a relatively small grammar. That is to say, there's not that many keywords in SQL. It's a pretty small language. But it's going to allow us to eliminate dozens of lines of Python code, perhaps. SQL follows this CRUD paradigm. So C-R-U-D, which simply means that in a relational database, you can really only do four things. You can create data, read data-- that is, look at it or analyze it somehow. Update the data, or delete the data. So, CRUD, for short. And that really speaks to just how relatively simple the world is, even though we'll just scratch the surface of some of its capabilities today.

And you'll explore more over time. Specifically, in SQL, there's going to be other keywords that map to those four ideas. Technically, you don't just create data in the world of SQL, you can also insert data, like inserting more rows into a sheet. And it's not the word "read" that people use. People say to "select" data. But they mean to read data, which is sort of the opposite of writing or creating data. But the U and the D are the same, except that there's also a keyword in SQL known as DROP, which lets you very destructively, very dangerously delete entire database tables, as well. So how do we do this, and what's the connection to our favorites data thus far? Well, here is the syntax in this language called SQL via which you can create a table. So the jargon is a little different, but the ideas are exactly the same from the world of spreadsheets. What you call a sheet in a spreadsheet, the database world calls a table.

It's a table of rows and columns, but it's the exact same idea. You're going to have discretion over what to call the table, just like you can call a spreadsheet something, or else, and you can also specify the types of data that you want to store in your rows and columns. And it's going to go a little more deeply than just formatting it, like in Excel, and Numbers, and Google Spreadsheets, you can actually control, maybe, how big the data could be depending on the database you're actually using. In CS50, we're going to use a light version of SQL. Literally, a language called-- an implementation of SQL called SQLite, which has really all of the core functionality that you would see in the real world, and with larger, more scalable systems, but it's going to allow us to focus on a lot of the building blocks. And SQLite's actually really popular on Macs, PCs, and phones, nowadays.

A lot of the data that games and other applications on your phone might store, actually have a file, a binary file with zeros and ones, that's in the SQLite format. So if you do a mobile app, for instance, for your final project, you'll have an opportunity to play with something like this. Well, how do you actually run SQLite3? It's just a command built into your code space. So this is a program you could install on your own Mac, your own PC, or the like. We'll do everything as we've done before, in the cloud, and actually use your code space. And by that I mean, we can just start to play with this data now using SQL instead of Python. So let me do this. Let me open up my terminal window here, and let me go ahead and maximize my terminal window just because we'll focus now on the files here. Recall that I have a file called favorites.csv, and that CSV file is just text. But let me load it into a proper database

so I can actually use this other language called SQL on it. To do this, I'm going to run SQLite3, which just means the third version of it, and I'm going to create a new database called favorites.db. That's just a convention, but it means here comes a database that I'm going to create. Notice, I'm not using the tabbed code editor. I'm not using the code command because the code command is generally for text files. SQLite3 is going to create a binary file, zeros and ones, ultimately. When I run that, it's going to ask me to verify yes. I'm going to hit y and then enter. And now I'm at the SQLite prompt, which is not the dollar sign. It literally says SQLite with an angled bracket. Now, one time only, I want to go ahead and load favorites.csv into this database so I can actually play around with it using not Python, but this new language called SQL. And the way I'm going to do this is as follows. I'm going to do dot. Mode csv, enter. And that just puts SQLite into CSV mode.

It has different modes for different file formats. I'm going to .import and then I'm going to specify the file that I want to import, which is favorites.csv. And then this one's up to me. What is the name of the table I want to create? And table, again, is essentially synonymous with sheets. So I'm going to call everything the same. I'm going to call my table favorites as well. So what this command is essentially going to do, is all of those lines of Python code that open the file, read it row by row, and do something with it-- This is just built into SQLite. It's going to load the whole darn CSV into this new favorites.db file, and then that's it for now. I'm going to go ahead and literally type .quit to get out of SQLite. I'm back at my dollar sign prompt. If I type ls, I have not only favorites.csv, I also have favorites.db now as well, a brand new file, and in that file now is

Ask anything

We've read this whole study set, so questions about it get the best answers.

FlashcardsQuizFill in the blanksWritten testLessonNotesPodcastContent