CS50 2021 in HDR - Lecture 6 - Python
Key Takeaways
Introduces Python programming language, covering its syntax, features, and applications
Full Transcript
[Music] all right this is cs50 and this is already week six and this is the week in which you learn yet another language but the goal is not just to teach you another language for language's sake as we transition today and in the coming weeks from c where we spent the past several weeks now to python the goal ultimately is to teach you all how to teach yourselves new languages so that by the end of this course it's not in your mind the the fact that you learned how to program and see or learned some weeks back how to program in scratch but really how you learned how to program fundamentally in a paradigm known as procedural programming as well as with some taste today and in the weeks to come of other aspects of programming languages like object oriented programming and more so recall though back in week 0 hello world looked a little something like this and the world was quite simple all you had to do was drag and drop these puzzle pieces but there were still functions and conditionals and loops and variables and all of those kinds of primitives we then transitioned of course to a much more arcane language that looked a little something like this and even now some weeks later you might still be struggling with some of the syntax or getting annoying bugs when you try to compile your code and it just doesn't work but there too the past few weeks we've been focusing on functions and loops and variables conditionals and really all of those same ideas and so what we begin to do today is to one simplify the language we're using transitioning from c now to python this now being the equivalent program in python and look at its relative simplicity but also transitioning to look at how you can implement these same kinds of features just using a different language so we're going to see a lot of code today and you won't have nearly as much practice with python as you did with c but that's because so many of the ideas are still going to be with us and really it's going to be a process of figuring out all right i want to do a loop i know how to do it in c how do i do this in python how do i do the same with conditionals how do i declare variables and the like and moving forward not just in cs50 but in life in general if you continue programming and learn some other language after the class if in five ten years there's a new more popular language that you pick up it's just gonna be a matter of googling and looking at websites like stack overflow and the like to look at just basic building blocks of programming languages because you already speak after these past six plus weeks you already speak programming itself fundamentally all right so let's do a few quick comparisons left and right of what something might have looked like in scratch and what it then looked like in c but now as of today what it's going to look like in python then we'll turn our attention to the command line ultimately in order to implement some actual programs so in scratch we had functions like this say hello world a verb or an action in c it looked a little something like this and a bit of a cryptic mess the first week you had the print f you had the double quotes you had the semicolon the parentheses so there's a lot more syntax just to do the same thing we're not going to get rid of all of that syntax now but as of today in python that same statement is going to look a little something like this and just to perhaps call out the obvious what is different or now simpler in python versus c even in this simple example here yeah good so it's now print instead of printf and there's also no semicolon and there's one other subtlety over here yeah so no new line and that doesn't mean it's not going to be printed it just turns out that one of the differences we'll see is that with print you get the new line for free it automatically gets outputted by default being sort of a common case but you can override it we'll see ultimately too how about in scratch we had multiple functions like this that not only said something on the screen but also asked a question there by being another function that returned a value called answer in c we saw code that looked a little something like this whereby that first line declares a variable called answer sets it equal to the return value of getstring one of the functions from the cs50 library and then the same double quotes and parentheses and semicolon then we had this format code in c that allowed us with percent s to actually print out that same value in python this 2 is going to look a little bit simpler instead we're going to have answer equals get string quote unquote what's your name and then print with a plus sign and a little bit of new syntax but let's see if we can't just infer from this example what it is that's going on well first missing on the left is what to the left of the equal sign there's no what this time feel free to just call it out so there's no type there's no type like the word string which even though that was a type in cs50 every other variable in c did we use int or string or float or bull or something else in python there's still going to be data types today onward but you the programmer don't have to bother telling the computer what types you're using the computer's going to be smart enough the language really is going to be smart enough to just figure it out from context meanwhile on the right-hand side getstring is going to be a function we'll use today and this week which comes from a python version of the cs50 library but we'll also start to take off those training wheels so that you'll see how to do things without any cs50 library moving forward using a different function instead as before no semi-colon but the rest of the syntax is pretty much the same here this starts of course to get a little bit different though we're using print instead of printf but now even though this looks a little cryptic perhaps if you've never programmed before cs50 what might that plus be doing just based on inference here what do you think [Music] yeah so adding answer to the string hello and adding so to speak not mathematically but in the form of joining them together much like we saw the join block in scratch or concatenation was the term of art there this plus sign appends if you will whatever's in answer to whatever is quoted here and i deliberately left the space there so that grammatically it looks nice after the comma as well now there's another way to do this and it too is going to look cryptic at first glance but it just gets easier and more convenient over time you can also change this second line to be this instead so what's going on here this is actually a relatively new feature of python in the past couple of years where now what you're seeing is yes a string between these same double quotes but this is what python would call a format string or f string and it literally starts with the letter f which admittedly looks i think a little weird but that just indicates that python should ensue assume that anything inside of curly braces inside of the string should be interpolated so to speak which is a fancy term saying substitute the value of any variables therein and it can do some other things as well so answer is a variable declared of course on this first line this f string then says to python print out hello comma space and then the value of answer if by contrast you avoi if you omitted the curly braces just take a guess what would happen what would the symptom of that bug be if you accidentally forgot the curly braces but maybe still had the f there yeah i would literally print hello comma answer because it's going to take you literally so the curly braces just kind of allow you to plug things in and again it looks a little more cryptic but it's just going to save us time over time and if any of you programmed in java in high school for instance you saw plus in that context too for concatenation this just kind of makes your code a little tighter a little more succinct so it's a convenient feature now in python all right this was an example in scratch of a variable setting a variable like counter equal to zero in c it looked like this where you specify the type the name and then the value with a semicolon in python it's going to look like this and i'll state the obvious here you don't need to mention the type just like before with string and you don't need a semicolon so it's a little simpler if you want a variable just write it and set it equal to some value but the single equal sign still behaves the same as in c suppose we wanted to increment counter by one in scratch we use this puzzle piece here in c we could do this actually in a few different ways there was this way if counter already exists you just say counter equals counter plus one there was the slightly less verbose way where you could whoops sorry let me do the first sentence first in python that same thing as you might guess is actually going to be almost the same you just throw away the semicolon and the mathematics are ultimately the same copying from right to left via the assignment operator now recall and see that we had this shorthand notation which did the same thing in python you can similarly do the same thing just no need for the semicolon the only step backwards we're taking if you were a big fan of counter plus plus that doesn't exist in python nor minus minus you just can't do it you have to do the plus equals one or plus minus or minus equals one to achieve that same result all right how about in python two here in scratch recall was a conditional asking a silly question like is x less than y and if so just say as much in c that looked a little something like this printf and if with the parentheses the curly braces the semicolon and all that in python this is going to get a little more pleasant to type two it's going to be just this and if someone wants to call it some of the obvious changes here what has been simplified now in python for a conditional it would seem yeah what's missing or chain so no curly braces and sorry and we're using the colon instead so i got rid of the curly braces in python but i'm using a colon instead and even though this is a single line of code so long as you indent subsequent lines along with the printf that's going to imply that everything if the if condition is true should be executed below it until you start to unindent and start uh writing a different line of code altogether so indentation in python is important so this is among the reasons we've emphasized uh axes like style just how well styled your code is and honestly we've seen certainly in office hours and you've seen in your own code sort of a tendency sometimes to be a little relaxed when it comes to indentation right if you're one of those folks who likes to indent everything on the left hand side of the window yeah it might compile and run but it's not particularly readable by you or anyone else python actually addresses this by just requiring indentation when logically needed so python is going to force you to start indenting properly now if that's been perhaps a tendency otherwise what else is missing well we have no semicolon here of course it's print instead of printf but otherwise those seem to be the primary differences what about something larger in scratch if an if else block like this you can perhaps guess what it's going to look like and see it looks like this curly braces semicolons and so forth in python it's going to now look like this almost the same but indentation's important the colons are important and there's one other difference that's now again visible here but we didn't call it out a second ago what else is different in python versus c for these conditionals yeah [Music] perfect we don't have any parentheses around the condition the boolean expression itself and why not well it's just simpler to type it's less to type you can still use parentheses and in fact you might want to or need to if you want to like combine thoughts and do this and that or this or that but by default you no longer need or should have those parentheses just say what you mean lastly with conditionals we had something like this an if else if else statement in c it looked a little something like this in python it's going to get really tighter now it's just if and this is the curiosity l if x greater than y so it's not else if it's literally one keyword l if and the colons remain now on each of the three lines but the indentation is important and if we did want to do multiple things we could just indent below each of these conditionals as well all right let me pause this first to see if there's any questions on these syntactic differences yeah [Music] in between between what and what ah good question is python uh sensitive to spaces and where they go sometimes no sometimes yes is the short answer stylistically though you should be practicing what we're preaching here whereby you do have spaces to the left and right of binary operators that they're called something like less than or greater than is a binary operator because there's two upper and to the left and to the right of them and in fact in python more so than the world of c there's actually formal style conventions not only within cs50 have we had style a style guide on the course's website for instance that just dictates how you should write your code so that it looks like everyone else is in the python community they take this one step further and there's an actual standard whereby you don't have to adhere to it but generally speaking in the real world someone would reprimand you would reject your code if you're trying to contribute it to another project if you don't hear to these standards so while you could be laxed with some of this white space do make things readable and that's python's theme for the code to be as readable as possible all right let's take a look at a couple of other constructs before transitioning to some actual code this of course in scratch was a loop meowing forever and see the closest we could get was doing something while true because true never changes so it's sort of a simple way of just saying do this forever in python it's pretty much the same thing but a couple small differences here the parentheses are gone the colon is there the indentation is there no semicolon and there's one other subtle difference what do you see true is capitalized just because both true and false are boolean values in python but you got to start capitalizing them just because all right how about a loop like this where you repeat something a finite number of times like meowing three times in c we could do this a few different ways there's this very mechanical way where you initialize a variable like i to zero you then use a while loop and check if i is less than three the total number of times you want to meow then you print what you want to print you increment i using this syntax or the longer more verbose syntax with plus equals or whatnot and then you do it again and again and again in python you can do it functionally the same way same idea slightly different syntax you just don't bother saying what type of variable you want python will infer from the fact that there's a zero right there you don't need the parentheses you do need the colon you do need the indentation you can't do the i plus plus but you can do this other technique as we could have done in c as well how else might we do this though too well it turns out in c we could do something like this which again sort of cryptic in at first glance became perhaps more familiar where you have an initialization a conditional and then an update that you do after each iteration in python there isn't really an analog there is no analog in python where you have the parentheses and the multiple semicolons in the same line instead there is a for loop but it's meant to read a little more like english 4i in 0 1 and 2. so we'll see in a bit these square brackets represent an array now to be called a list in python so lists in python are more like linked lists than they are in a they are arrays more on that soon so this just means for i in the following list of three values and on each iteration of this loop python automatically for you it first sets i to zero then it sets i to one then it sets i to two so that you effectively do things three times but this doesn't necessarily scale as i've drawn it on the board suppose you took this at face value as the way you iterate some number of times in python using a for loop at what point does this approach perhaps get bad or bad design let me give folks just a moment to think yeah i'm back [Music] sure if you don't know how many times you want to loop or iterate you can't really create a hard-coded list like that of zero one two other thoughts [Music] yeah if you're iterating a large number of times this list is gonna get longer and longer and you're just kind of stupidly gonna be typing out like comma three comma four comma five comma dot dot comma ninety nine comma 100 i mean your code would start to look atrocious eventually so there is a better way in python there is a function or technically a type called range that essentially magically gives you back a range of values from zero on up to but not through a value so the effect of this line of code for i in the following range essentially hands you back a list of three values thereby letting you do something three times and if you want to do something 99 times instead you of course just change the three to a 99 question a really good question can you start counting at a higher number so not zero which is the implied default but something larger than that yes so it turns out the range function takes multiple arguments not just one but maybe two or even three that allows you to customize this behavior so you can customize where it begins you can customize the increment by default it's one but if you want to do every two values for like evens or odds you could do that as well and a few other things and before long we'll take a look at some python documentation that will become your authoritative source for answers like that like what can this function do other questions on this thus far seeing none so what else might we uh compare and contrast here well in the world of c recall that we had a whole bunch of built-in data types like these here um bull and char and double and float and so forth string which happened to come from the cs50 library but uh the the language c itself certainly understood the idea of strings because the backslash zero the support for percent s and printf that's all native built into c not a cs50 simplification all we did and revealed as of a couple of weeks ago is that string this data type is just a synonym for a type def for char star which is part of the language natively in python now this list actually gets a little shorter at least for these common primitive data types still going to have bulls we're going to have floats and ins and we're going to have strings but we're going to call them stirs and this is not a cs50 thing from the library stir str is in fact a data type in python that's going to do a lot more than strings did for us automatically in c ins and floats meanwhile [Music] don't need the corresponding longs and doubles because in fact among the problems python solves for us too ants can get as big as you want integer overflow is no longer going to be an issue per week one the language solves that for us floating point and precision unfortunately is still a problem that remains but there are libraries code that other people have written as we briefly discussed in weeks past that allow you to do scientific or financial computing using libraries that build on top of these data types as well so there's other data types too in python which we'll see actually gives us a whole bunch of more power and capability things called ranges like we just saw lists like i called out verbally with the square brackets things called tuples for things like x comma y or latitude comma longitude dictionaries or dicks which allow you to store keys and values much like our hash tables from last time and then sets in the mathematical sense where they filter out duplicates for you and you can just put a whole bunch of numbers a whole bunch of words or whatnot and the language via this data type will filter out duplicates for you now there's going to be a few functions we give you this week and beyond training wheels that we're then going to very quickly take off just because as we'll see today they just simplify the process of getting user input correctly without accidentally writing buggy code just when you're trying to get hello world or something similar to work and will give you functions not like not as long as this list in c but a subset of these get float get int and get string that'll automate the process of getting user input in a way that's more resilient against potential bugs but we'll see what those bugs might be and the way we're going to do this is similar in spirit to c instead of doing include cs50.h like we did in c you're going to now start saying import cs50 python supports similar to c libraries but there aren't header files anymore you just use the name of the library in python and if you want to import cs50s functions you just say import cs50 or if you want to be more precise and not just import the whole thing which could be slow if you've got a really big library with a lot of functionality in it you can be more precise and say from cs50 import get flow from cs50 import get int from cs50 import get string or you can just separate them by commas and import three and only three things from a particular library like ours but starting today and onward we're going to start making much more heavy use of libraries code that other people wrote so that we're no longer reinventing the wheel we're not making our own linked lists our own trees our own dictionaries we're going to start standing on the shoulders of others so that you can get real work done so to speak faster by building your software on top of other's code as well all right so that's it for the syntactic tour of the language and the sort of core feature soon we'll transition to application thereof but let me pause here to see if there's any questions on syntax or primitives or otherwise or otherwise oh yes and back oh sorry say again why doesn't python have what kind of operators [Music] sorry someone coughed when you said something operators the oh the increment operator i'd have to check the history honestly python has tended to be a fairly minimalist language and if you can do something one way the community arguably has tended to not give you multiple ways to do the same thing syntactically there's probably a better answer and i'll see if i can dig in and post something online to follow up on that all right so before we transition to now writing some actual code let me go ahead and consider exactly how we're going to write code in the world of c recall that it's generally been a two-step process we create a file called like hello.c and then step one make hello step two dot slash hello or if you think back to week two when we sort of peeled back the layer of what hello of what make was doing you could more verbosely type out the name of the actual compiler clang in our case command line arguments like dash oh hello to specify what name you want to create and then you can specify the file name and then you can specify what libraries you want to link in so that was a very verbose approach but it was always a two-step approach and so even as you've been doing recent problem sets odds are you've realized that anytime you want to make a change to your code or make a change to your code and try and test your code again you're constantly doing those two steps moving forward in python it's going to become simpler and it's going to be just this the file name is going to change but that might go without saying it's going to be something like hello.pi py instead of hello.c and that's just a convention using a different file extension but there's no compilation step per se you jump right to the execution of your code and so python it turns out is the name not only if the language we're going to start using it's also the name of a program on a mac a pc assuming it's been pre-installed that interprets the language for you this is to say that python is generally described as being interpreted not compiled and by that i mean you get to skip from the programmer's perspective that compilation step there is no manual step in the world of python typically of writing your code and then compiling it to zeros and ones and then running the zeros and ones instead these kind of two steps get collapsed into the illusion of one whereby you instead are able to just run the code and let the computer figure out how to actually convert it to something the computer understands and the way we do that is via this whole process input and output but now when you have source code it's going to be passed into an interpreter not a compiler and the best analog of this is just to perhaps point out that in the human world if you speak or don't speak multiple human languages it can be a pretty slow process from going from one language to another for instance here are step-by-step instructions for finding someone in a phone book unfortunately in spanish unfortunately if you don't speak or read spanish you could figure this out you could run this algorithm but you're going to have to do some googling or you're going to have to open a literal dictionary from spanish to english and convert this and the catch with translating any language human or computer or otherwise is that you're going to pay a price typically some time and so converting this in spanish to this in english is just going to take you longer than if this were already in your native language and that's going to be one of the subtleties with the world of python yes it's a feature that you can just run the code without having to bother compiling it manually first but we might pay a price and things might be a little slower now there's ways to chip away at that but we'll see an example there of in fact let me transition now to just a couple of examples that demonstrate how python is not only easier for many people to use perhaps yourselves too because it throws away a lot of the annoying syntax it shortens the number of lines you have to write and also it comes with so many darn libraries you can just do so much more without having to write the code yourself so as an example of this let me switch over here to this image from problem set four which is the weeks bridge down by the charles river here in cambridge and this is the original photo pretty clear and it's even higher res if we looked at the original version of the photo but there have been no filters a la instagram applied to this photo recall for problem set four you had to implement a few filters and among them might have been blur and blur was probably among the more challenging of the ones because you had to iterate over all of the pixels you had to take into account what's above what's below to the left to the right i mean there was a lot of math and arithmetic and if you ultimately got it it was probably a great sense of satisfaction but that was probably several hours later in a language like python where there might be libraries that have been written by others on whose shoulders you can stand we could perhaps do something like this let me go ahead and run a program or write a program called blur dot pi here and in blur dot pi in vs code let me just do this let me import from a library not the cs50 library but the pillow library so to speak a keyword called image and another one called image filter then let me go ahead and say let me open the current version of this image which is called bridge.bmp so the before version of the image will be the result of calling image.open quote unquotebridge.bmp and then let me create an after version so you'll see before and after after equals the before version dot filter of image filter and there is if i read the documentation i'll see that there's something called a box blur that allows you to blur in box format like one pixel above below left and right so i'll do one pixel there and then after that's done let me go ahead and save the file as something like out.bmp that's it assuming this library works as described i am opening the file in python using line three and this is somewhat new syntax in the world of python we're gonna start making use of the dot operator more because in the world of python you have what's called object oriented programming or oop as a term of art and what this means is that you still have functions you still have variables but sometimes those functions are embedded inside of the variables or more specifically inside of the data types themselves think back to c when you wanted to convert something to uppercase there was a two upper function that takes as input an argument that's a char and you can pass in any chart you want and it will uppercase it for you and give you back a value well you know what if that's such a common paradigm where uppercasing chars is a useful thing what the world of python does is it embeds into the string data type or char if you will the ability just to uppercase any char by treating the char or the string as though it's a struct in c recall that structs encapsulate multiple types of values in object oriented programming in a language like python you can encapsulate not just values but also functionality functions can now be inside of structs but we're not going to call them structs anymore we're going to call them objects but that's just a different vernacular so what am i doing here inside of the image library there's a function called open and it takes an argument the name of the file to open once i have a variable called before that is a struct or technically an object inside of which is now because it was returned from this function a function called filter that takes an argument the argument here happens to be image dot box blur one which itself is a function but it just returns the filter to use and then after dot save does what you might think it just saves the file so instead of using f open and if right you just say dot save and that does all of that messy work for you so it's just what four lines of code total let me go ahead and go down to my terminal window let me go ahead and show you with ls that at the moment well sorry let me not bother showing that because i have other examples to come i'm going to go ahead and do python of blur dot pi nope sorry wrong place i did need to make a command there we go okay let me go ahead and type ls inside of my filter directory which is among the sample code online today there's only one file called bridge.b damn i'm trying to get these things ready at the same time let me rewind let me move this code into place all right i've gone ahead and moved this file blur.pi into a folder called filter inside of which there's another file called bridge.bmp which we can confer with ls let me now go ahead and run python which is my interpreter and also the name of the language and run python on this file so much like running the spanish algorithm through google translate or something like that as input to get back the english output this is going to translate the python language to something this computer or this cloud-based environment understands and then run the corresponding code top to bottom left to right i'm going to go ahead and enter no error message is generally a good thing if i type ls you'll now see out.bmp let me go ahead and open that and you know what just to make clear what's really happening let me blur it even further let's make a box that's not just one pixel around but 10. so let's make that change and let me just go ahead and rerun it with python of blur.pi i still have out.bmp let me go ahead and open out.bmp and show you first the before which looks like this that's the original and now crossing my fingers four lines of code later the result of blurring it as well so the library is doing all of the same kind of leg work that you all did for the assignment but it's encapsulated it all into a single library that you can then use instead those of you who might have been feeling more comfortable might have done a little something like this let me go ahead and open up one other file called edges.pi and in edges.i i'm again going to import from the pillow library the image keyword and the image filter then i'm going to go ahead and create a before image that's a result of calling image.open of the same thing bridge.bmp then i'm going to go ahead and run a filter on that called image whoops image filter dot find edges which is like a constant if you will defined inside of this library for us and then i'm going to do after dot save quote unquote out dot bmp using the same file name i'm now going to run python of edges.pi after sorry user error we'll see what syntax error means soon let me go ahead and run the code now edges.pi let me now open that new file out.pnp and before we had this and now especially if what will look familiar if you did the more comfortable version of pset four we now get this after just four lines of code so again suggesting the power of using a language that's better optimized for the tool at hand and at the risk of really making folks sad let's go ahead and re-implement if we could problem set five real quickly here let me go ahead and open another version of this code wherein i have a c version just from problem set five when you implemented a spell checker loading a hundred thousand plus words into memory and then you took kept track of just how much time and memory it took and that probably took a while implementing all of those functions in dictionary.c let me instead now go into a new file called dictionary.pi and let me stipulate for the sake of discussion that we already wrote in advance dot pi which corresponds to speller.c you didn't write either of those recall for problem set five we gave you speller.c assume that we're gonna give you speller.pie so the onus on us right now is only to implement speller dictionary dot pi all right so i'm going to go ahead and define a few functions and we're going to see now the syntax for defining functions in python i want to go ahead and define a first a hash table which was the very first thing you defined in dictionary.c i'm going to go ahead then and say words gets this give me a dictionary otherwise known as a hash table all right let me define a function called check which was the first function you might have implemented check is going to take a word and you'll see in python the syntax is a little different you don't specify the return type you use the word def instead to define you still specify the name of the function and the any arguments there too but you will omit any mention of types but you do use a colon and indent so how do i check if a word is in my dictionary or in my hash table well in python i can just say if word in words go ahead and return true else go ahead and return false done with the check function all right now i want to do like load that was the heavy lift where you had to load the big file into memory so let me define a function called load it takes a string the name of a file to load so i'll call that dictionary just like in c but no data type let me go ahead and open a file uh by using an open function in python by opening that dictionary in read mode so this is a little similar to f open a function in c you might recall then let me iterate over every line in the file in python this is pretty pleasant for line in file colon indent how now do i get at the current word and then strip off the new line because in this file of words 140 000 words there's word backslash n word backslash n all right well let me go ahead and get a word from the current line but strip off from the right end of the string the new line which the r strip function in python does for me then let me go ahead and add to my dictionary or hash table that word done let me go ahead and close the file for good measure and then let me go ahead and return true because all was well that's it for the load function in python how about the size function this did not take any arguments it just returns the size of the hash table or dictionary in python i can do that by returning the length of the dictionary in question and then lastly gone from the world of python is malloc and free memory is managed for you so no matter what i do there's nothing to unload the computer will do that for me so i give you in these functions problems at five in python so i'm sorry we made you write it in c first but the implication now is that what are you getting for free in a language like python well encapsulated in this one line of code is much of what you wrote for problem set five implementing your array for all of your letters of the alphabet or more all of the linked lists that you implemented to create chains to store all of those words all of that is happening it's just someone else in the world wrote that code for you and you can now use it by way of a a dictionary and actually i can change this a little bit because add is technically not the right function to use here i'm actually treating the dictionary as something simpler a set so i'm going to make one tweak set recall was another data type in python but set just allows it to handle duplicates and it allows me to just throw things into it by literally using a function as simple as add and i'm gonna make one other tweak here because when i'm checking a word it's possible it might be given to me in uppercase or capitalized it's not going to necessarily come in in the same lowercase format that my dictionary did i can force every word to lowercase by using word dot lower and i don't have to do it character for character i can do the whole darn string at once by just saying word dot lower all right let me go ahead and open up a terminal window here and let me go into first my c version on the left and actually i'm going to go ahead and split my terminal window into two and on the right i'm going to go into a version that i essentially just wrote but it's also available online if you want to play along afterward i'm going to go ahead and make speller in c on the left and note that it takes a moment to compile then i'm going to be ready to run speller of dictionaries let's do like the sherlock holmes text which is pretty big and then over here let me get ready to run python of speller on texts homes.txt2 so the syntax is a little different at the command prompt i just on the left have to compile the code with make and then run it with dot slash speller on the right i don't need to compile it but i do need to use the interpreter so even though the lines are wrapping a little bit here let me go ahead and run it on the right and i'm going to count how long it takes verbally for demonstration sake one mississippi two mississippi three mississippi okay so it's like three seconds give or take now running it in python keeping in mind i spent way fewer hours implementing a spell checker in python than you might have in problem set five but what's the trade-off going to be and what kinds of design decisions do we all now need to be making consciously here we go on the right in python one mississippi two mississippi three mississippi four mississippi five mississippi six mississippi seven mississippi eight mississippi nine mississippi ten mississippi eleven mississippi all right so ten or eleven seconds so which one is better let's like go to the group here which of these programs is the better one how might you answer that question based on demonstration alone what do you [Music] programmer or think comfortable for the programmer but c is better for the user okay so python to summarize is better for the programmer because it was way faster to write but c is maybe better for the computer because it's much faster to run i think that's a reasonable formulation other opinions yeah i think it depends on the size [Music] whereas at c if i'm dealing with something like a massive data set or something huge that that time is going to really build up on it might be worth it to put in the upfront effort and just go to the ac so the process continually runs faster over absolutely a really good answer and let me summarize is it depends on the workload if you will if you were to you if you have a very large data set you might want to optimize your code to be as fast and performant as it can be especially if you're running that code again and again maybe you're a company like google people are searching a huge database all the time you really want to squeeze every bit of performance as you can out of the computer you might want to have someone smart take a language like c and write it at a very low level it's going to be painful they're going to have bugs they're going to have to deal with memory management and like but if and when it works correctly it's going to be much faster it would seem by contrast if you have a data set that's big and 140 000 words is not small but you don't want to spend like five hours 10 hours a week of your time building a spell checker or a dictionary you can instead leverage a different language with different libraries and build on top of it in order to prioritize the human time instead other thoughts [Music] that perfect segue to exactly the next point we wanted to make which was is there something in between and indeed there is i'm oversimplifying what this language is actually doing it's not as stark a difference as saying like hey python is four times slower than c like that's not the right takeaway there are absolutely ways that engineers can optimize languages as they have already done for python and in fact i've configured my settings in such a way that i've kind of dramatized just how big the difference is it is going to be slower python typically than the equivalent c program but it doesn't have to be as big of a gap as it is here because indeed among the features you can turn on in python is to save some intermediate results technically speaking yes python is interpreting dictionary.pi and these other files translating them from one language to another but that doesn't mean it has to do that every darn time you run the program as you propose you can save or cache c-a-c-h-e the results of that process so that the second time in the third time are actually notably faster and in fact python itself the interpreter the most popular version thereof itself is actually implemented in c so you can make sure that your interpreter is as fast as possible and what then is maybe the high level takeaway yes if you are going to try to squeeze every bit of performance out of your code and maybe code is constrained you maybe you have very small devices maybe it's like a watch nowadays or maybe it's a sensor that's installed in some small format in an appliance or in infrastructure where you don't have much battery life and you don't have much size you might want to minimize just how much work is being done and so the faster the code runs and the better it's going to be if it's implemented something low level so c is still very commonly used for certain types of applications but again if you just want to solve real world problems and get real work done and your time is just as if not more valuable than the device you're running it on long term you know what python is among the most popular languages as well and frankly if i were implementing a spell checker moving forward i'm probably starting with python and i'm not going to waste time implementing all of that low-level stuff because the whole point of using newer modern languages is to use abstractions that other people have created for you and by abstraction i mean something like the dictionary function that just gives you a dictionary or hash table or the equivalent version that i used which in this case was a set all right any questions then on python thus far no all right let's oh yeah in the middle [Music] [Music] really good question or observation could you just compile python code yes absolutely this idea of compiling code or interpreting code is not native to the language itself it tends to be native to the conventions that we humans use so you could actually write an interpreter for c that would read it top to bottom left to right converting it to on the fly something that computer under the computer understands but historically that's not been the case c is generally a compiled language but it doesn't have to be what python nowadays is actually doing is what you described earlier it technically is sort of unbeknownst to us compiling the code technically not into zeros and ones technically into something called bytecode which is this intermediate step that just doesn't take as much time as it would to recompile the whole thing and this is an area of research for computer scientists working in programming languages to improve these kinds of paradigms why well honestly for you and i the programmer it's just much easier to one run the code and not worry about the stupid second step of compiling it all the time why it's literally half as many steps for me the human and that's a nice thing to optimize for and ultimately two you might want all of the fancy features that come with these other languages so you should really just be fine-tuning how you can enable these features as opposed to shying away from them here and in fact the only time i personally ever use c is from like september to october of every year during cs50 almost every other month do i reach for python or another language called javascript to actually get real work done which is not to impugn c it's just that those other languages tend to be better fits for the amount of time i have to allocate and the types of problems that i want to solve all right let's go ahead and take a five minute break here and when we come back we'll start writing some programs from scratch all right so let's go ahead and start writing some code from the beginning here whereby we start small with some simple examples and then we'll build our way up to more sophisticated examples in python but what we'll do along the way is first look side by side at what the c code looked like way back in week one or two or three and so forth and then write the corresponding python code at right and then we'll transition just to focusing on python itself what i've done in advance today is i've downloaded some of the code from the course's website my source six directory which contains all of the pre-written c code from weeks past but it'll also have copies of the python code we'll write here together and look at so first here is hello dot c back from week zero this was version zero of it i'm gonna go ahead and do this i'm gonna go ahead and split my uh code window up here i'm going to go ahead and create a new file called hello.pi and this isn't something you'll typically have to do laying your code out side by side but i've just clicked the little icon in vs code that looks like two columns that splits my code editor into two places so that we can in fact see things for now side by side with my terminal window down below all right now i'm going to go ahead and write the corresponding python program on the right which recall was just print quote unquote hello world and that's it now down in my terminal window i'm going to go ahead and run python of hello.pi enter and voila we've got hello.pi working so again i'm not going to play any further with the c code it's there just to jog your memory left and right so let's now look at a second version of hello world from that first week whereby if i go and get hello1.c i'm going to drag that over to the right whoops i'm going to go ahead and drag that over to the left here and now on the right let's modify hello.pi to look a little more like the second version in c all right i want to get a uh answer from the user is a return value but i also want to get some input from them so from cs50 i'm going to import the the function called get string for now we're going to get rid of that eventually but for now it's a helpful training wheel and then down here i'm going to say answer equals get string quote unquote what's your name question mark space but no semicolon no data type and then i'm going to go ahead and print just like the first example on the slide hello comma space plus answer and now let me go ahead and run this pythonflow.pi all right it's asking me what's my name david hello comma david but it's worth calling attention to the fact that i've also simplified further it's not just that the individual functions are simpler what is also now glaringly omitted from my python code at right both in this version and the previous version what did i not bother implementing yeah so i didn't even need to implement main we'll revisit the main function because having a main function actually does solve problems sometimes but it's no longer required and see you have to have that to kick start the entire process of actually running your code and in fact if you were missing main as you might have experienced if you accidentally compiled helpers.c instead of the file that contained main you would have seen a compiler error in python it's not necessary python you can just jump right in start programming and boom you're good to go especially if it's a small program like this you don't need the added overhead or complexity of a
Original Description
This is CS50, Harvard University's Introduction to the intellectual enterprises of computer science and the art of programming. Enroll for free at https://cs50.edx.org/. Slides, source code, and more at https://cs50.harvard.edu/x. Playlist at https://www.youtube.com/playlist?list=PLhQjrBD2T383f9scHRNYJkior2VvYjpSL.
TABLE OF CONTENTS
00:00:00 - Introduction
00:01:17 - Python
00:03:42 - Syntax
00:18:19 - Types
00:20:48 - CS50 Library
00:22:55 - Compilation and Interpretation
00:26:55 - blur.py
00:33:00 - dictionary.py
00:45:17 - hello.py
00:49:57 - calculator.py
00:55:25 - Exceptions
01:00:49 - Floating Point Imprecision
01:02:17 - points.py
01:05:49 - agree.py
01:13:00 - meow.py
01:21:44 - mario.py
01:38:23 - Documentation
01:41:45 - scores.py
01:45:59 - uppercase.py
01:49:56 - Command-line Arguments
01:54:10 - Exit Status
01:56:34 - numbers.py
01:57:40 - names.py
01:58:49 - Dictionaries
02:05:33 - CSV Files
02:16:20 - Speech Synthesis
02:18:04 - Facial Recognition
02:20:53 - Speech Recognition
02:22:31 - QR Codes
02:23:46 - This was CS50
***
This is CS50, Harvard University's introduction to the intellectual enterprises of computer science and the art of programming.
***
HOW TO SUBSCRIBE
http://www.youtube.com/subscription_center?add_user=cs50tv
HOW TO TAKE CS50
edX: https://cs50.edx.org/
Harvard Extension School: https://cs50.harvard.edu/extension
Harvard Summer School: https://cs50.harvard.edu/summer
OpenCourseWare: https://cs50.harvard.edu/x
HOW TO JOIN CS50 COMMUNITIES
Discord: https://discord.gg/cs50
Ed: https://cs50.harvard.edu/x/ed
Facebook Group: https://www.facebook.com/groups/cs50/
Faceboook Page: https://www.facebook.com/cs50/
GitHub: https://github.com/cs50
Gitter: https://gitter.im/cs50/x
Instagram: https://instagram.com/cs50
LinkedIn Group: https://www.linkedin.com/groups/7437240/
LinkedIn Page: https://www.linkedin.com/school/cs50/
Medium: https://cs50.medium.com/
Quora: https://www.quora.com/topic/CS50
Reddit: https://www.reddit.com/r/cs50
Watch on YouTube ↗
(saves to browser)
Sign in to unlock AI tutor explanation · ⚡30
Playlist
Uploads from CS50 · CS50 · 0 of 60
← Previous
Next →
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
Hello, World: Hadi Partovi
CS50
Content Distribution and Archival in a Digital Age
CS50
CS50 2014 - Week 1
CS50
CS50 2014 - Week 3
CS50
CS50 2014 - Week 0, continued
CS50
CS50 2014 - Week 4
CS50
Week 3, continued
CS50
Quiz 0 Review
CS50
CS50 2014 - Week 3, continued
CS50
CS50 2014 - Week 7
CS50
CS50 2014 - Week 7, continued
CS50
Breaking Through The (Google) Glass Ceiling by Christopher Bartholomew
CS50
Introduction to Amazon Web Services by Leo Zhadanovsky
CS50
CS50 2014 - Week 9
CS50
How to Build Innovative Technologies by Abby Fichtner
CS50
Light Your World (with Hue Bulbs) by Dan Bradley
CS50
Building Dynamic Web Apps with Laravel by Eric Ouyang
CS50
CS50 2014 - CS50 Lecture by Steve Ballmer
CS50
CS50 2014 - Week 10
CS50
This is CS50 with Steve Ballmer?
CS50
Meteor: a better way to build apps by Roger Zurawicki
CS50
Data Analysis in R by Dustin Tran
CS50
Data Visualization and D3 by David Chouinard
CS50
CS50 2014 - Week 6
CS50
Build Tomorrow's Library by Jeffrey Licht
CS50
CS50 2014 - Week 9, continued
CS50
Essential Scale-Out Computing by James Cuff
CS50
iOS App Development with Swift by Dan Armendariz
CS50
Sam Clark Leads Yale Students on Tour to CS50 at Harvard
CS50
3D Modeling and Manufacture by Ansel Duff
CS50
CS50 2014 - Week 5, continued
CS50
hello, world
CS50
CS50 2014 - Deep Thoughts - Hash Table
CS50
CS50 2014 - Deep Thoughts - Binary Tree
CS50
CS50 2014 - Deep Thoughts - Scratch
CS50
CS50 2014 - Deep Thoughts - MySQL
CS50
LaunchCode Visits CS50
CS50
CS50 Live, Episode 100
CS50
CS50 Field Trip to Google
CS50
This is CS50 AP
CS50
Week 4: Monday - CS50 2011 - Harvard University
CS50
Week 2: Wednesday - CS50 2011 - Harvard University
CS50
Week 1: Wednesday - CS50 2011 - Harvard University
CS50
Week 11: Monday - CS50 2011 - Harvard University
CS50
Week 3: Wednesday - CS50 2011 - Harvard University
CS50
Week 12: Monday - CS50 2011 - Harvard University
CS50
Week 1: Friday - CS50 2011 - Harvard University
CS50
Week 3: Monday - CS50 2011 - Harvard University
CS50
Week 10: Wednesday - CS50 2011 - Harvard University
CS50
Week 2: Monday - CS50 2011 - Harvard University
CS50
Week 9: Monday - CS50 2011 - Harvard University
CS50
Week 7: Monday - CS50 2011 - Harvard University
CS50
Week 5: Monday - CS50 2011 - Harvard University
CS50
Week 5: Wednesday - CS50 2011 - Harvard University
CS50
Week 7: Wednesday - CS50 2011 - Harvard University
CS50
Week 8: Monday - CS50 2011 - Harvard University
CS50
Week 9: Wednesday - CS50 2011 - Harvard University
CS50
Week 8: Wednesday - CS50 2011 - Harvard University
CS50
Week 10: Monday - CS50 2011 - Harvard University
CS50
Week 2: Wednesday - CS50 2010 - Harvard University
CS50
Related Reads
📰
📰
📰
📰
Tokenmaxxing And The Future Of AI Inference: The New Cost Curve
Forbes Innovation
The Vibe Coding Hangover, Part 2: Your AI Didn't Just Write Bugs, It Wrote Backdoors
Dev.to · Courage Labhani Paul
TypeScript for Python Developers: A Practical Guide
Dev.to · qing
How to Build a Good Human-in-the-Loop for AI Coding Agents
Dev.to · Brenn Hill
Chapters (30)
Introduction
1:17
Python
3:42
Syntax
18:19
Types
20:48
CS50 Library
22:55
Compilation and Interpretation
26:55
blur.py
33:00
dictionary.py
45:17
hello.py
49:57
calculator.py
55:25
Exceptions
1:00:49
Floating Point Imprecision
1:02:17
points.py
1:05:49
agree.py
1:13:00
meow.py
1:21:44
mario.py
1:38:23
Documentation
1:41:45
scores.py
1:45:59
uppercase.py
1:49:56
Command-line Arguments
1:54:10
Exit Status
1:56:34
numbers.py
1:57:40
names.py
1:58:49
Dictionaries
2:05:33
CSV Files
2:16:20
Speech Synthesis
2:18:04
Facial Recognition
2:20:53
Speech Recognition
2:22:31
QR Codes
2:23:46
This was CS50
🎓
Tutor Explanation
DeepCamp AI