CS50 2020 - Lecture 6 - Python
Skills:
Python for Data80%
Key Takeaways
Introduces the Python programming language, covering variables, data types, functions, and control structures
Full Transcript
[Music] [Music] all right this is cs50 and this is week six and this is again one of those rare days where in just a bit of time you'll be able to say uh that you learned a new language and that language today is going to be this language called python and we thought we'd begin by introducing python by way of some more familiar friends so this of course is where we began the course back in week 0 when we introduced scratch a simple program that quite simply says hello world and then very quickly things escalated and became a lot more cryptic a lot more arcane and we introduced c and syntax like this which of course do the exact same thing just printing out hello world on the screen but with the requirement that you understand and you include all of this various syntax so today all of this complexity all of the the syntax from c suddenly begins to uh melt away such that we're left with this new language called python that's going to achieve the exact same goal simply with this line of code here which is to say that python tends to be more accessible it tends to be a little easier but that's because it's built on this tradition of having started as humans years ago building these low-level languages like c realizing what features are missing what some of the pain points are and then layering on top of those older languages new ideas new features and in turn new languages so there are dozens hundreds really of programming languages out there but there's always a subset of them that tend to be very popular very in vogue at any given time python is among those very popular languages and it's the third of our languages that we'll look at indeed at this point in the term so let's go ahead and introduce some of the syntax of python really by way of comparison with what we've seen in the past because no matter how new some of today's topics are they should all be familiar in the sense that we're going to see loops again conditions variables functions return values there's pretty much just going to be a translation of features past to now features present so this of course in the world of scratch was just one puzzle piece or a function whose purpose in life is to say hello world on the screen in week one we translated this to the more cryptic syntax here key details being that it's printf uh that you have to quote the string hello world you have this backslash n to record represent a new line character and then of course this kind of statement has to end with a semicolon the equivalent line of code today on out in this language called python is going to be quite simply this so it looks similar certainly but it's now print instead of printf we still have the double quotes but gone are the backslash n as well as the semicolon so if you've been kicking yourself all too frequently for forgetting stupid things like the semicolons uh python is will now be your friend well let's take a look at another example here how we might go about getting user input as well well here notice that we have a puzzle piece called ask and it says ask what's your name and wait and the next puzzle piece said whatever the human had typed in preceded with the word hello in c we saw code like this string answer equals get string what's your name and then printing out with printf hello percent s plugging in one value for the other in python some of this complexity is about to melt away too and in python we're going to see a little something like this so no longer present is the mention of the type of variable no longer present is the semicolon at the end and no longer present is the percent s and that additional argument to print so in fact let's go ahead and see these things in action i'm going to go ahead and go over to cs50 ide here for just a moment and within cs50 ide i'm going to go ahead and write my very first python program and to do that i'm going to go ahead and create a file that will initially called hello.pi much like in the world of c python programs have a standard file extension being dot pi instead of dot c and i'm just going to do what i proposed was the simplest translation i'm just going to go ahead and say and print hello comma world i'm going to save my file and then i'm going to go down to my terminal window and in the past of course we would have used make and then we would have done dot slash hello or the like but today i'm quite simply going to run a command that itself is called python i'm going to pass in the name of the file i just created as its command line argument and voila hitting enter there is my very first program in python so that's pretty powerful let's go ahead and create this second program that i proposed a moment ago instead of just printing out hello world the whole time i'm also going to go ahead this time and give myself a variable that i'll call answer i'm going to go ahead now and get input from the user and i'm going to go ahead and use the familiar get string that we did cnc i'm going to go ahead and ask what's your name question mark i'm not going to bother with a semicolon but down here i'm going to go ahead and say print hello comma and then a space inside of the quotes and instead of doing something like percent s i'm actually going to go ahead and just do a plus operator and then literally the word answer but the catch is that this isn't going to work just yet this isn't going to work just yet because get string it turns out just like it doesn't come with c it also doesn't come with python so i need to do one thing that's going to be a little bit different from the past instead of hash including something i'm going to literally say from cs50 import getstring so in the world of c recall that we included cs50.h which had declarations for functions like getstring and getint and so forth in the world of python we're going to do something similar in spirit but the syntax is just a little different we're going to say from cs50 which is our python library that we the staff wrote import that is include a function specifically called getstring and now any errors that i might have seen a moment ago on the screen have disappeared if i go ahead and save this file and now do python space hello dot pi and hit enter now i can go ahead and type in my actual name and voila i see hello comma david so let's tease apart what's different about this code and consider what more we can do after this so again notice on line three there's no mention of string anymore if i want a variable i just go ahead and give myself a variable called answer the function is still called getstring and it still takes an argument just like the c version but the line no longer ends with a semicolon on my final line of code here print it's now indeed print instead of printf and then this is new syntax but in some sense it's going to be a lot more straightforward instead of having to think in advance where i want the percent s and my placeholder this plus operator seems to be doing something for me and let me go ahead and ask a question of the group here what does that plus operator seem to be doing because it's not addition in the arithmetic sense if we're not like adding numbers together but the plus is clearly doing something that gives us a visual result any thoughts from uh peter what's this plus doing it's concatenating strings yeah it's concatenating strings which is the term of art to describe the joining of one string and the other so it's quite like therefore scratch's own join block we now have a literal translation of that join block which we didn't have in c in c we had to use printf we had to use percent s python is going to be a little more user friendly such that if you want to join two strings like hello comma space and the contents of that variable we can just use this plus operator instead and the last thing that we had to do was of course import this library so that we have access to the getstring function itself well let's go ahead and take a tour of just some other features of python and then dive in primarily to a lot of hands-on examples today so recall that in uh the example we just saw we had this first line of code which gets a string from the user stores it in a variable called answer we had the second line of code which is peter notes concatenates two values together but it turns out even though this is definitely more convenient than in c in that you can just take an existing string and another and join them together without having to use format strings or the like well it turns out there's another way there's frankly many ways in languages like python to achieve the same result and i'm going to go ahead and propose that we now change this line here to this funky syntax so definitely ugly at first glance and that's partly because this is a relatively new feature of python but notice that in python can we use these curly braces so curly braces that we have used in c to plug in an actual value of a variable here so instead of percent s python's print function uses these curly braces that essentially say plug in a value here but there's one oddity here you can't just start putting curly braces and variable names into strings that is quoted strings in python you also have to tell the language that what follows is a formatted string so this is perhaps the weirdest thing we've seen yet but when you do have a pair of double quotes like i have here prefixing it with an f will actually tell the computer to format the contents of that string plugging in values between those curly braces as opposed to literally printing those curly braces themselves so let me go ahead and transition to my actual code here and try this out instead of using the concatenation operator as peter described it this plus operator let me literally go ahead and say hello comma answer initially so this is probably not going to be the right approach because if i rerun this program python of hello.pi it's going to ask me what's my name i'm going to type in david and it's going to ignore me altogether because i've literally hard coded hello comma answer but it's also not going to be quite right to just start putting that in curly braces because if i again run this program python of hello.pi and type in my name now it's going to say hello squigglybrace answer so here is just a subtle change where i have to tell python that this type of string between the double quotes is in fact a formatted string and now if i rerun python if hello.pi and type in david i now get hello david so it's marginally more convenient than c because again you don't have to have a placeholder here a placeholder here and then a comma separated list of additional arguments so it's just a more succinct way if you will to actually introduce more values into a string that you want to create these are called format strings or for short f strings and it's a new feature that we now have in our toolkit when programming with this new language called python well let's take a look at a few other translation of puzzle pieces to see and then turn to python and then start building some programs of our own so here in scratch this was an example early on of a variable called counter initializing it to zero in c in week one we started translating that to code like this int counter equals zero semicolon and that gave us a variable of type int whose initial value was zero in python the code's gonna be similar similar but it's gonna be a little simpler still notice that i don't have to in python mention the type of variable i want it will infer from context what it is and i also don't have to have the semicolon there so counter equal 0 in python is going to give you a variable called counter and because you're assigning it the value zero python itself the language will infer that oh you must mean this to be an int or an integer what else did we see in scratch change counter by one so this was a way of increasing the value of a variable by one in c we had a few different ways to implement this we could say counter equals counter plus one it's kind of pedantic it's kind of long and tedious to type so instead we had some shorthand notation that allowed us to do it uh this way instead in pi in c we were able to do counter plus equals one and that was going to achieve the same result well in python we actually have a couple of approaches as well we can much like in c say it explicitly like this but just omit the semicolon so counter equals counter plus one the logic in python is exactly the same as in c and as for this shorthand notation this also exists in python again without the semicolon the one thing that does not exist in python in at this point in the story is that fancy counter plus plus syntax or i plus plus that syntactic sugar that made it even more succinct to just increment a variable unfortunately does not exist in python but you can do counter plus equals one or whatever your variable happens to be well what else did we see in scratch and then c recall this we introduced of course conditions pretty early on and those conditions use boolean expressions to decide whether to do this or this other thing or something else altogether in c you we converted this to what looked kind of similar and indeed the curly braces kind of hug the printf line just like the yellow condition here hugs the purple say block and we had parentheses around the boolean expression like x less than y we again used printf inside of the curly braces which had double quotes a backslash n for a new line and a semicolon python nicely enough is going to be sort of identical in spirit but simpler syntactically what python is going to look like henceforth is just this so the parentheses around the x less than y go away the curly braces go away the new line goes away and the semicolon goes away and here you see just a tiny example of evolution of humans programming languages right if you and i have been frustrated for some time about all the stupid semicolons and curly braces all over the place it makes it harder in some sense for your code to read let alone being correct humans decided when inventing new languages that you know what why don't we just say what we mean and not worry as much about all of this syntactic complexity let's keep things simpler and indeed that's what we see here is one example in python but there's a key detail if any of you have been in the habit when writing code in c of being a little sloppy when it comes to your indentation and maybe style 50 is constantly yelling at you to add spaces add spaces or remove spaces or lines well in python it is now necessary to indent your code correctly in c of course we cs50 and a lot of the world in general recommend that you indent your code by four spaces typically or one tab in the context of python you must do so if you accidentally omit these spaces just to the left of the print statement here your python code is not going to run at all the python program just won't work so no more sloppiness python is going to impose this on you but the upside is you don't have to bother including the curly braces what about a more complicated condition where there's two uh paths you can follow if or else well in this case in c we translated it pretty straightforwardly like this again parentheses up here curly braces here and here backslash n backslash n and semicolon you can perhaps guess in python that this is going to get a little more compact because boom now we don't need the parentheses anymore we do need to indent but we don't need the curly braces we don't need the new line and we don't need the semicolon so we're sort of shedding features that can be taken now for granted but what about this example in scratch when we had a three-way fork in the road if else if else well in python or rather in c we would have translated this like this and there's not much going on there but it's a pretty substantive number of lines of code some 12 lines just to achieve this simple idea in python notice what's going to go away here is again those parentheses again those curly braces again the backslash n and the semicolon there's only one oddity here there's only one oddity what looks wrong or weird to you maybe what looks like a typo to you and i promise i haven't screwed up here maybe elsewhere but not here uh andrew um i would say the lift instead of elsif is different syntactically exactly so whereas in c we would literally say else if in python humans years ago decided heck why say else if and waste all that time typing that out if you can more succinctly say l-if as one word e-l-i-f so indeed this is correct syntax here and you can have more of those you can have four uh bran four uh forks in the road five six any number thereafter but the syntax is indeed a little different but it's a little tighter right there's less syntactic distraction when you glance at this code you don't have to ignore as many semicolons and curly braces in the life like python tends to just be a little cleaner syntactically and indeed that's characteristic of a lot of more recent more modern languages like it all right let's take a look at a few other blocks in scratching and turn c in scratch when we wanted to do something again and again as a loop perhaps forever we would literally use the forever block in c we could implement this in a few different ways and we proposed quite simply this one while true print out hello world again and again and again and because the boolean expression never changes it's going to indeed execute forever so python's actually pretty similar but there are a couple of subtle differences so in grain in your mind what this looks like here we have true in parentheses the curly braces the new line the semicolon a lot of that's about to go away but there's still going to be a slight difference notice that we're indenting as i keep emphasizing we no longer have the new line or the semicolon or the curly braces but true and it turns out false now must be capitalized so whereas in c it was lowercase false lowercase true in python it's going to be capitalized false capitalize true why just because but there is one other detail that's important to note both with our loops here as well as with our conditions just as before if i rewind to our most recent condition notice that even though we've gotten rid of the curly braces and we've gotten rid of the parentheses we now have introduced these colons which are necessary after this expression this expression and this one to make clear to python that the lines of code that follow indented underneath are indeed relevant to that if elif or else and we see that same feature again here in the context of a loop well we saw other loops of course in scratch when we wanted to do something a finite number of times like three we would repeat the following three times in c we had a few different approaches to this and all of them i dare say were very mechanical like if you want to do something three times the onus in c is on you to like declare a variable keep track of how many times you've counted already increment the thing like there's a lot of moving parts and so in c one approach looked like this we declare a variable called i equals zero but we could call it anything we want we have a while block here that's asking a boolean expression again and again is i less than zero is i less than three and then inside of the loop we printed out hello world and using c's syntactic sugar the plus plus notation we kept adding one to i add one to i at one to i until we implicitly break out of the loop because it's of course no longer less than 3. so in python similar in spirit but again some of that clutter goes away i equals 0 is all we need say to give ourselves a variable while i less than 3 is all we need to say there but with the colon then inside of that indented properly we print out hello world and we can't do the plus plus so we minor disappointment but i plus equals 1 increments i so this would be one way of implementing in python the exact same thing a loop that executes three times but we saw other approaches of course in c and there's other approaches possible in python as well you might recall in c that we saw this approach the for loop and odds are you've been reaching for the for loop pretty frequently because even though it looks a little more cryptic you can pack more features into that one line of code in between those those semicolons if you will so same exact logic it just prints out this hello world three times using a for loop instead in python things start to get a little elegant here now it's a little weird at first glance but it's definitely more succinct if you want to do something three times it turns out in python you can use a more succinct syntax for the for loop for i in and then in square brackets a list of values so just as we used in the past square brackets and a few different places to connote arrays and indexing into arrays in the world of python whenever you surround a bunch of values that themselves have commas in between them and you encapsulate them all using square brackets that's what we're going to call in python a list and it's very similar in spirit to an array but we'll call it in the context of python a list and so what this line of code says is for i in012 what does that mean this is a for loop in python that says give me a variable called i and on the first iteration of this loop set i equal to zero on the second iteration of this loop set i equal to one and on the last iteration of this loop set i equal to two for me it just does all of that for you now at the end of the day it actually doesn't matter what i is per se because i'm not printing the value of i and that's totally fine odds are you've used for loops or you did something again and again like printing hello world even though you didn't print out the value of i so technically i could have put any three things in these square brackets if i want but the convention would be just enumerate just like in c zero one two just like a computer scientist counting from zero but this could break down pretty easily this could become very ugly very quickly does anyone see a problem with for loops in python if you have to put in between those square brackets the list of values that you want to iterate over uh noah um if you want to do for example like a thing 50 times you'd have to write out zero one two three four five six yeah my god it would start to look hideous quickly and it's funny you mentioned 50 because in preparing this this demonstration for lecture today i went back to week zero when actually the analog in week zero was to indeed print out hello world 50 times and i thought to myself damn it like this is going to look atrocious now because i literally have to put inside of square brackets 0 1 2 3 4 5 6 7 8 9 all the way to 49 as noah says which would just look atrocious like surely there's got to be a better way and there is while this might be compelling for very short values there's a simpler way in python when you want to do something some number of times we can replace this list of three values with this a function called range that takes an input which is the number of things that you want to return and essentially what range will do for you past an input like three it will automatically generate for you a list of three values zero one and two and then python will iterate over those three values for you so to know as a concern a moment ago if i now want to iterate 50 times i just change the 3 to a 50 and i don't have to create this crazy mess of a manually typed out list of 0 through 49 which of course would not be a very well designed a program it would seem just because of the the length of it and the opportunity to mess up and the like so in python this is perhaps now if you will the most pythonic way to do something some number of times and indeed this is a term of art in the python community long story short technical people programmers they tend to be pretty religious in some sense when it comes to the right way of doing things and indeed within the world of python programming a lot of python programmers do have both opinions but also standardized recommendations that dictate how you should write python code and tricks like this are what are considered pythonic you are doing something pythonically if you're doing it the quote-unquote right way which doesn't mean right in the absolute it means right in the sense that most other people rather agree with you in this sense all right let's see a few final features of python before we now start to build some of our own features in c recall we had this whole list of data types and there are more and you can create your own of course but the primitives that we looked at initially were these bull char double float int long string and so forth in python even though i haven't needed them because i can give myself a variable like a string or an int just by giving it a name like counter or i or answer and then assigning it a value and python infers from what you're assigning it what data type it should be python does have data types it's just what's known in in the programming world as a loosely typed language in the world of c c is a strongly typed language where not only do types exist you must use them explicitly in the world of python you have what's called a loosely typed language which in which types exist but you can often infer them implicitly the burden is not on you the programmer to specify those data types incessantly let the computer figure it out for you so this is our list from c this now is going to be our analogous list in the world of python we're going to have bull still true is and false but capital t capital f we're going to have floats which are real numbers with decimal points we're going to have ins which of course are numbers like negative 1 0 and 1 and so forth and then not strings per se but stirs str and whereas in the world of c there was technically no string type that was a feature offered by the cs50 library which just made more accessible the idea of a char star recall that c has strings and they're called strings but there's no data type called string the way you give yourself a string of course in c is to declare something as a char star and in cs50's library we just gave that char star a synonym a nickname an alias called string in python there are actual there is an actual data type for strings and for short it's called str all right so with that said what other features do we have from python that we can use here well there's other data types as well in python that are actually going to prove super useful as we begin to develop more sophisticated programs and do even cooler things with the language we've seen range already strictly speaking this is a data type of sorts within python that gives you back a range of values by default zero on up based on the input you provide list i keep mentioning verbally a list is a proper data type in python that's similar in spirit to arrays but whereas in arrays recall we've spent great emphasis over the past few weeks noting that arrays are a fixed size you have to decide in advance how big that array is going to be and like last week if you decide oops i need more memory you have to dynamically allocate more space for it copy values over and then free up the old memory like there's so much jumping through hoops so to speak when you want to use arrays and c if you want to grow them or even shrink them python and other higher level languages like it do all of that for you so a list is like an array that automatically resizes itself bigger and smaller that feature now you get for free in the language so to speak you don't have to implement it yourself python has what are called tuples in the context of like math you might have or gps you might have x and y coordinates or latitude and longitude coordinates so like comma separated values tuples are one way of implementing those in python dict or dictionaries so python has dictionaries that allow you to store keys and values or literally in our human world if you have a human dictionary here for instance for english much like a dictionary in physical form lets you store words and their definitions a dictionary in python more generally lets you store any keys and any values you can associate one thing with another and we'll see that this is a wonderfully useful and versatile data structure and then lastly for today's purposes there's these things called sets which if you recall from math a set is a collection of values like abc or 123 without duplicates but python manages that for you you can add items to a set you can remove items from a set python will make sure that there are no duplicates for you and it will manage all of the memory for you as well so what we have uh in the way of functions meanwhile is a few familiar friends recall that in c we use the cs50 library to get chars doubles floats ins longs and strings in python thankfully we don't have to worry about doubles or longs anymore more on that in a bit but the cs50 library for python which you saw me import a few minutes ago does give you a function called get float it does give you a function called getint it does give you a function called getstring that at least for this week's purposes are just going to make your life easier these two are training wheels that we will very quickly take off so that you're only using native python code ultimately and not cs50s own library but for the sake of transitioning this week from c to python you'll find that these will just make your life easier before we relax and take those away too so in c to use the library you had to include cs50.h in python again you're going to go ahead and import cs50 or more explicitly the specific function that you might want to import so it turns out there's different ways to import things they ultimately achieve essentially the same goal you can with lines like this explicitly import one function at a time like i did earlier using get string or you can import the whole library all at once by just saying more succinctly import cs50 it's going to affect the syntax we have to use hereafter but there we'll see multiple ways of doing this in our examples here on out you can also simplify this a bit and you can import a comma separated list of functions from a library like ours and this is a convention we'll see quite frequently as well because as we start using uh popular third-party libraries written by other programmers on the internet they will very commonly give us lots of functions that we ourselves can use and we will be able to import those one after the other by just specifying them here in this way all right let me pause here just to see if there's any questions on python syntax like that's essentially it for our crash course in python syntax we're now going to start building things and explore what the features of python are and what some of the nuances are and really the power of python but first any questions on on syntax we've seen loops conditions variables olivia question or comment um if in a for loop if you want to increment by something besides one but you don't want to explicitly type out the list how would you do that really good question so if you wanted to use a for loop and iterate over a range of values but you wanted that range to be 0 2 4 6 8 instead of 0 two three let me go ahead and go back to that slide from a moment ago and i can actually change this on the fly let me go into that slide which was right here and what i can do actually is specify another value which might be this if i change if i change the input to range to be not one value but two values that's going to be a clue to the computer that it should count a total of three values but it should increment two at a time instead of the default which is one and there's even other capabilities there too you don't have to start counting at zero you can adjust that as well which is to say that with python you're going to find a lot more features come with the language and even more powerfully the functions that you can write and the functions that you can use in python also can take different numbers of arguments sometimes it's zero sometimes it's one sometimes it's two but it's ultimately often up to you good catch other questions will we see sequences like primarily in the for loops or are there other applications where they're very useful sequences in what sense in the sense of ranges or lists or something else um yeah in terms of ranges good question will we use them in other contexts generally speaking it's pretty rare i mean i'm i'm racking my brain now as to other use cases that i have used range for and i'm sure i could come up with something but i think hands down the most common case is in the context of iteration as in a for loop and i'll think on that to see other applications but anytime you want to generate a long list of values that follow some pattern whether it's 0 1 2 or as olivia points out a range of values with gaps range will allow you to avoid having to hard code it entirely and you can actually write your own generator function so to speak a function that returns whatever pattern of values that you want other questions or confusion anything on your end brian from the chat or beyond uh looks like all the questions are answered here all right well let's go ahead now and do something more interesting than hello world because after all this is where programming really gets fun really gets powerful when you and i no longer have to implement those low level implementation details when you had to implement memory management for your hash table or memory management for a linked list or copying values in array we've been spent the past several weeks focusing really on some low-level primitives that are useful to understand but they're not fun to write and i i can see that they might not be fun to write in problem set form and they're certainly not going to be fun to write for the rest of your life every time you want to just write code to solve some problem but again that's where libraries come in and now this is where other languages come in it turns out that python is a much better a much easier language to use for solving certain types of problems among them some of the problems you we have been solving in past problem sets so in fact let me go ahead and do this i'm going to go ahead and grab a file here give me one moment called bridge.bitmap which you might recall from a past problem set this is a beautiful week's bridge down by the charles river in cambridge mass by harvard and this is a very clear photograph taken by one of cs50's team members and in recent weeks of course you wrote code to do all sorts of mutations of this image among them blurring the image and blur i dare say was not the easiest problem to solve you had to sort of look up down left and right sort of average all of those pixels you had to understand how an image is represented one pixel at a time so there's a lot of low level minutiae there when at the end of the day all you want to do is just blur an image so whereas in past weeks we sort of had to think at and write at this lower level now with python it turns out we're going to have the ability to think at a higher level of abstraction and write far less code for ourselves so let me go ahead and do this i'm going to use my mac for this instead of cs50 ide just so i can open the images more quickly this is to say that even though we'll continue using cs50 ide for python and for other languages over the remainder of the course you can also install the requisite software on a mac on a pc sometimes even kind of sort of a phone today to use python and sort of c in other languages on your own devices but again we tend to use cs50 ide during the class so as to have a standard environment that just works so i'm going to go ahead and write though on my computer a program called blur.pi pi of course being the file extension for python programs that my program looks a little different now i've got this black and blue and white window but this is just a text editor on my own personal mac here i'm going to go ahead and do this i need to have some functionality related to images in order to blur an image so i'm going to go ahead and import from a pill library a pillow library so to speak a special feature called image and a special feature called image filter that is to say these are essentially two functions that someone else smarter than me when it comes to image manipulation wrote they made their code freely available on the internet free and open source which means anyone can use the code and i am allowed now to import it into my program because i before class downloaded and installed it beforehand now i'm going to go ahead and do this i'm going to give myself a variable called before and i'm going to call image.open on bridge.bmp so again even though we've never seen this before never used this before you can kind of glean syntactically what's going on i've got a variable on the left called before i've got a function on the right called image.open and i'm passing in the name bridge.bitmap so it sounds like this is kind of like f open in the world of c now notice this dot is kind of serving a new role here in the past we've used the dot operator only for structs in c when we want to go into a person object or into a a node object and we want to go inside of it and access some variable therein well it turns out in python you have things similar in spirit to structs in c but instead of containing only variables or data like name and number like we did for the person struct a few weeks back in python you can have inside of a structure not only data that is variables you can also have functions inside of structures and that starts to open up all sorts of possibilities in terms of features available to you so it seems that i've got this image object this image struck that i've again imported from someone else inside of it is an open function that expresses input the name of a file to open so we'll see this syntax increasingly over the course of today's examples let me give myself a second variable after let me go ahead now and assign to this variable called after the results of calling that before images filter function passing in image filter dot box blur of one now this is a little cryptic and we're not going to spend time on this particular syntax because odds are in life you're not going to have that many opportunities to want to blur an image for which you're going to run or write code but for today's purposes notice that inside of my before variable because i assigned it the return value of this new feature it has inside of it not just data but also functions one of them now called filter and this filter function takes as input the return value of some other function call that long story short will blur my image using a box of uh with a one pixel radius so just like your own code if you implemented blur and c this code is going to tell my code to look up down left and right and blur the pixels by taking the average around them and that's kind of it after that i'm going to do after dot save and i'm going to save this as like out.bmp i just want to create a new file called out.bmp and if i've made no mistakes let me go ahead now and run python of blur.pi and hit enter no error messages so that's usually a good thing if i type ls now notice that i've got bridge.bmp which i already opened blur.pi which i just wrote and out.bmp and if i go ahead and open out.bmp let's go ahead and take a look here's before here's after huh before after now over the internet it probably doesn't look that blurred though on my mac right here a few inches away it definitely looks blurred but let's do it a little more compellingly how about instead of looking one pixel up down left and right why don't we look 10 pixels at a time so we really blur it by looking at more values and averaging more let me go ahead now and run python of blur.pi now let me go ahead and reopen and now you see before and after before and after so what is this to say well here is what problem set four in four lines of code blurring an image so pretty cool pretty powerful by standing on the shoulders of others and using their libraries can we do other things quite quickly notice what i can also do here too is solve a more recent problem let me go over to a different directory where i have an advanced and you can download these files off of the course's website a few files that we wrote before class one is called speller.pie so long story short in speller.pie is a translation from c into python the code for speller.c recall that that was part of the distribution code for problem set 5 and in speller.c we translated it now to speller.pie and in dictionaries and in texts we see the same files as in problem set five two different size dictionaries and a whole bunch of short and long texts what hasn't been created yet is the equivalent of dictionary.c aka now dictionary.pi so let me go ahead and implement my spell checker in python let me go ahead and create a file called dictionary.pi as is again the convention and let's go ahead we have to implement four functions right we have to implement check load size and unload but i probably need like a global variable here to store my dictionary and this is where you all implemented your hash table with a pointer and then linked lists and arrays and all of that a lot of complexity you know what i'm just going to go ahead and give myself a variable called words and declare it as a set so recall that a set is just a collection of values that handles duplicates for you and frankly that's all i really need i need to be able to store all of the words in a dictionary and just throw them into a set so that there's no duplicate values and i can just check is one word in the set or is it not well let's go ahead now and load words into that set i'm going to go ahead and define a function called load that takes the name of a file to open and here is submittedly some new syntax so thus far we've only typed code into the file itself in fact the most striking difference thus far dare say about python versus c is that i have never once even written a main function and that too is a feature of python if you want to write a program you don't have to bother writing your default code in a function called main just start writing your code and that's how we were able to get hello world down from this many lines of code in c to one line in python we didn't even need to have main but if i want to define my own functions it turns out in python you use the keyword def for define then you put the name of the function and then in parentheses like in c you put the names of the variables or parameters that you want the function to take you don't have to specify data types though and again we don't use curly braces we're instead using a colon so this says hey python give me a function called load that takes an argument called dictionary and what should this function do well the purpose of the load function in speller was to load each word from the dictionary and somehow put it into your hash table i'm going to go ahead and do the same read each word from the dictionary and put it into this so-called set my variable called words so i'm going to go ahead and open the file which i can do with this function here in python you don't use f open you just use a function called open and i'm going to assign the return value of open to a variable called file but i could call that anything i want this is where python gets really cool recall that reading the lines from python from the file in c was kind of arduous right you had to use like uh f read or some other function in order to read character after character after character one line at a time well here in python you know what if i want to iterate over all of the lines in a file we'll just say for line in file this is going to automatically give me a for loop that initial that assigns the variable line to each successive line in the file for me it will figure out where all of those lines are what do i want to do with each line well i want to go ahead and add to my set of words that line insofar as each word rep each line represents a word i just want to add to my global variable words that line and that's not quite right because what's at the end of every line in my file every line in my file by definition has a backslash n right that is why all of the words in the big dictionary we gave you are one per line so how do you get rid of the new line at the end of a a string well in c my god we would have to like use malloc to make a copy and then move all of the characters over and then shorten it a little bit by getting rid of the backslash n uh-uh in python if you want to strip off the new line at the end of a string just do r strip to strip characters means by default to strip off white space white space includes the space bar the tab character and backslash n so if you want to take each line and throw away the trailing new line at the end of it you can simply say line dot r strip and this is where strings again in python are powerful because they are their own data type they have inside of them not only all of the characters composing the string but also functions like r strip which strips from the end of the line any white space that might be there uh you know what after this i think i'm done i'm just going to go ahead and close the file and i'm going to go ahead and return true so that's it that's the load function in python open the dictionary for each line in the file add it to your global variable close the file return true i mean i'm pretty sure that my code is probably several lines and certainly many hours shorter than your code might have been for implementing that as well well what about checking right maybe the complexity is just elsewhere well let me go ahead and define a function called check that takes a specific word as input as its argument and then i'm just going to check if that given word is in my set of words well it turns out in c you would probably have to use a for loop or a while loop and you'd have to iterate over the whole list of words that you've loaded using binary search or linear search or like like i'm so past that at this point so many weeks in i'm just going to say if word in words go ahead and return true else return false and that now is my implementation of check now it's a little buggy and i will fix this does anyone spot the bug even if you've never seen python before but having spent hours implementing your own version of check is there some step i'm missing logically there is a bug here does anyone spot what i'm not doing that you probably did do when checking if a given word is in fact in the dictionary a couple people are commenting on case sensitivity yeah case sensitivity so odds are in your implementation in c you probably forced the word to all uppercase or you forced it to all lowercase totally doable but you probably had to do it like character for character you might have had to copy the input using malloc or putting it into an array character for character then using uh a two upper or two lower to capitalize or lowercase each individual letter like oh like that would take forever as indeed it might have so you know what if you want to take a given word and lowercase it just say word.lower and python will take care of all of those steps of iterating over every character changing each one to lowercase and returning to you the new result and indeed this now i would think is consistent with what you did in your example as well well how about size well in size recall that you had to define a function that doesn't take any inputs but returns the number of words in the set of words and i'm going to go ahead here and actually i got my indentation slightly off here let me fix this real fast if you want to return the size of your dictionary or really the number of words in your set you can just return the length of that global variable words done and lastly if you want to unload the dictionary let me go ahead and unload things doesn't take input as well honestly because i've not done any equivalent of malloc i've not done any memory management why you don't have to in python i can literally just return true in all cases because my code is is undoubtedly correct because i didn't have to bother with pointers and addresses in memory management so all of the stress that might have been induced over the past few weeks as you understood the lower level details of memory management now go away not because not because uh it's not happening underneath the hood but because python is doing it for you and i did spot one bug here actually notice i kind of relapsed into c code here i what i should have said here is it's actually file.close so here when i close the file and load i actually have to call file.close because now that function close is associated with that variable for me so again there is memory management happening malloc and free or reallock are all happening sort of for you underneath the hood but what python the language is doing for you now is managing all of that for you that's what you get by using a so-called higher level language instead of a lower level language you get more features and in turn in this case you get all of those problems taken care of for you so that you and i can focus on building our spell checker so you and i can focus on building our instagram filters not on allocating memory copying strings uppercasing things which honestly while it might have been fun and very gratifying the first time you got
Original Description
TABLE OF CONTENTS
00:00:00 - Introduction
00:00:49 - Python
00:04:14 - hello.py
00:05:03 - Variables
00:08:33 - F-strings
00:13:12 - Conditions
00:17:28 - Loops
00:24:43 - Types
00:26:46 - Sequence Types
00:29:01 - CS50 Library
00:34:39 - blur.py
00:40:40 - dictionary.py
00:53:44 - Interpreter
00:58:21 - range
01:02:43 - input
01:04:07 - addition.py
01:10:12 - division.py
01:11:46 - conditions.py
01:15:02 - agree.py
01:21:13 - meow.py
01:28:40 - positive.py
01:32:51 - mario.py
01:38:43 - Integer Overflow
01:41:10 - Floating-Point Imprecision
01:41:50 - scores.py
01:48:44 - uppercase.py
01:51:00 - argv.py
01:54:57 - exit.py
01:57:41 - numbers.py
01:58:49 - names.py
02:00:32 - phonebook.py
02:04:09 - Dictionaries
02:06:57 - swap.py
02:08:54 - CSV Files
02:13:41 - hogwarts.py
02:21:03 - Speech Synthesis
02:24:05 - Facial Recognition
02:27:50 - QR Codes
02:29:45 - Speech Recognition
02:36:05 - Deepfakes
***
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/T8QZqRx
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/
Reddit: https://www.reddit.com/r/cs50/
Quora: https://www.quora.com/topic/CS50
Slack: https://cs50.edx.org/slack
Snapchat: https://www.snapchat.com/add/cs50
Twitter: https://twitter.com/cs50
YouTube: http://www.youtube.com/cs50
HOW TO FOLLOW DAVID
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
More on: Python for Data
View skill →Related Reads
📰
📰
📰
📰
Software Engineer Interview Process at AI Startups
Medium · AI
Software Engineer Interview Process at AI Startups
Medium · Machine Learning
Software Engineer Interview Process at AI Startups
Medium · Data Science
Building a Deepfake Detection System That Actually Explains Its Decisions
Medium · Machine Learning
Chapters (40)
Introduction
0:49
Python
4:14
hello.py
5:03
Variables
8:33
F-strings
13:12
Conditions
17:28
Loops
24:43
Types
26:46
Sequence Types
29:01
CS50 Library
34:39
blur.py
40:40
dictionary.py
53:44
Interpreter
58:21
range
1:02:43
input
1:04:07
addition.py
1:10:12
division.py
1:11:46
conditions.py
1:15:02
agree.py
1:21:13
meow.py
1:28:40
positive.py
1:32:51
mario.py
1:38:43
Integer Overflow
1:41:10
Floating-Point Imprecision
1:41:50
scores.py
1:48:44
uppercase.py
1:51:00
argv.py
1:54:57
exit.py
1:57:41
numbers.py
1:58:49
names.py
2:00:32
phonebook.py
2:04:09
Dictionaries
2:06:57
swap.py
2:08:54
CSV Files
2:13:41
hogwarts.py
2:21:03
Speech Synthesis
2:24:05
Facial Recognition
2:27:50
QR Codes
2:29:45
Speech Recognition
2:36:05
Deepfakes
🎓
Tutor Explanation
DeepCamp AI