CS50x 2023 - Lecture 6 - Python

CS50 · Beginner ·👁️ Computer Vision ·3y ago

Key Takeaways

Introduces Python programming, including compilation, interpretation, and basic syntax

Full Transcript

foreign [Music] foreign [Music] [Applause] [Music] [Applause] foreign [Music] this is cs50 and this is week six wherein we finally transition from scratch to C to now Python and indeed this is going to be somewhat of a unique experience and that just like a few weeks passed perhaps for the first time and now uh today you're going to learn a new language but the goal isn't just to throw another fire hose of content and syntax and whatnot at you but rather to really equip you all to actually teach yourself new languages in the future and so indeed what we'll do today what we'll do this coming week is sort of prepare you to stand on your own and once python is passe and the world has moved on to some other language in some number of years you'll be well equipped to figure out how to wrap your mind around some new syntax some new language and solve problems as well now you'll recall in week zero this is where we started just saying hello to the world and that quickly escalated just a week later in C to be something much much more cryptic and if you've still sort of struggled with some of the syntax find yourself checking your notes or your previous code like that's total normal and that's one of the reasons why there are languages besides C out there among them this language called python humans over the decades have realized gee that wasn't necessarily the best design decision or humans have realized wow you know what now that computers have gotten faster with more memory and more faster CPUs we can actually do more with our programming languages so just as human languages evolve so do actual programming languages and even within a programming language there's typically different versions We for instance have been using version C11 of C which was updated in 2011 um but python itself continues to evolve and it's now up to version three plus and so there too these things will evolve in the coming days thankfully what you're about to see is hello world for the third time but it's going to be literally this none of the crazy syntax above or below fewer semicolons if any fewer curly braces and really a lot of the distractions get out of the way so to get there let's consider exactly how we've been programming up until now so you write a program in C and you've got hopefully no syntax error so you're ready to build it that is compiled and so you've run make and then you've run the program like dot slash hello or if you think back to week two where we took a peek underneath the hood of what make is doing it's really running the actual compiler something called clang maybe with some command line arguments creating a program called hello and then you could do dot slash hello so today you're going to start doing something similar in spirit but fewer steps no longer will you have to compile your code and then run it and then maybe fix or change it and then compile your code and run it and then repeat repeat the process of running your code is going to be distilled into just a single step and the way to think of this for now is that whereas C is frequently used as indeed a compiled language whereby you convert it first to zeros and ones Python's going to let you speed things up whereby you the human programmer don't have to compile it you're just going to run what's called an interpreter which by Design is named the exact same thing as the language itself and and by running this program installed in vs code or eventually on your own Macs or PCS this is just going to tell your computer to interpret this code and figure out how to get down to that lower level of zeros and ones but you don't have to compile the code yourself anymore so with that said let's consider what the code is going to look like side by side in fact let's look back at some scratch blocks just like we did with C in week one and do some side by sides because even though some of the syntax this week and Beyond is going to be different like the ideas are truly going to be the same there's not all that much intellectually new just yet so whereas in week zero we might have said hello to the world with this purple puzzle piece today of course or rather in week one it looked like this in C but today moving forward it's going to quite simply look like this instead and if we go back and forth for just a moment here again is the version in C noticing the very C like characteristics and just at a glance here in Python I claim it's now this what do you apparently need not worry about anymore what's gone so semicolon is gone and indeed you don't need those to finish most of your thoughts anymore anything else so the backslash n is absent and that's kind of curious because we're still going to get a new line but we'll see that it's become the default and this one's a little more subtle but now the function is called print instead of printf so it's a little more familiar in that sense all right so when it comes to using libraries that is code that other people have written in the past we've done things like hash include cs50.h to ucs50 Zone header file or standard IO or standard lib or string or any number of other header files you have all used but moving forward we're going to give you for this first week a similar cs50 Library just very short-term training wheels that will quickly take off because in reality it's a lot easier to do things in python as we'll see but the syntax for this now is going to be to import the cs50 library in this way and when we have now this ability we can actually start writing some code right away in fact let me switch over to vs code here and just as in the past I'll create a new file but instead of creating something called dot C I'm going to go ahead and create my first program called hello.pi using code code space Hello dot Pi that of course gives me this new tab and let me actually quite simply do what I proposed print quote unquote hello world without the backslash n without the semicolon without the F in print and now let me go down to my terminal window and I don't have to compile it I don't have to do dot slash i instead run a program called python whose purpose in life is now to interpret my code top to bottom left to right and if I run python of hello.pi crossing my fingers as always voila now I have printed out hello world so we seem to have gotten the new line for free in this sense where it's automatically happening the dollar sign isn't weirdly on the same line like it once was in week one but that's just a minor detail here if we switch back to now some other capabilities well indeed with the cs50 library you can also not just import the library itself but specific functions and you'll see that temporarily we're going to give you a helper function called get string just like in C that just makes it work exactly the same same way as in C and we'll see a couple of other functions that will just make life easier initially but quickly will we take those training wheels off so that nothing is indeed cs50 specific all right well how about functions more generally in Python let's do a whirlwind tour if you will much like we did in that first week of C comparing one to the other so back in our world of scratch one of the first programs we wrote was this one here whereby we asked the human their name we then use the return value that was sort of automatically stored in this answer variable as and second argument to join so that we could say hello David or hello Carter so this was back in week one uh week zero in week one we converted it to this and here's a perfect example of things like escalating quickly and again this is why we start in scratch there's just so much distraction here to achieve the same idea but even today we're going to chip away at some of that syntax so in C we had to declare the argument as we had to declare the variable as a string here we of course had the semicolon and more well in python the comparable code now is going to look more simply like this so semicolon is again gone on both lines for that matter so that's good what else appears to have changed or disappeared yeah yeah so I didn't have to specifically say that answer is now a string and indeed python is is dynamically typed and in fact it will infer from Context exactly what it is you are storing in that variable other details that seem a little bit different a little bit different what else jumps out at you here I'll go back this was the C version and maybe Focus now on the second line because we've rather exhausted the first here's now the python version what's different here yeah yeah there's no percent second argument at the moment per se to print now it is still a little weird it's as though I've like deployed some addition here arithmetically but that's not the case some of you have programmed before and plus some of you might know means what in this context so to combine or more technically anyone know the buzzword yeah to concatenate so to concatenate is like the fancy way of what scratch calls joining which is to take one string on the left one string on the right and to join them together to glue them together if you will so this is not addition it would be if it were numbers involved instead but because we've got a string hello comma and another string implicitly in this variable based on what the human typed in in response to this get string function that's going to concatenate hello comma space and then David or Carter or whatever the human has typed in but it turns out there's going to be different ways to do this in Python and we'll show you a few different ones and here too try not to get too hung up or on or frustrated by like all of the different ways you can solve problems odds are you're going to be picking up tips and techniques for years to come if you continue programming so let's just give you a few of the possible ways so here's a second way you could print out hello comma David or hello comma Carter but what has changed in the previous version I used concatenation explicitly and the space here is important grammatically just so we get that in the final phrase now I'm proposing to get rid of that space to add a comma outside of the double quotes as well but if you think back to C this probably just means that print similar in spirit to printf can take not just one argument but even two and in fact because of this comma in the middle that's outside of the double quotes it's hello comma and then it will be automatically concatenated with even without using the plus to whatever the value of answer is and by default just for grammatical prettiness the print function always gives you a space for free in between each of the multiple arguments you pass in we'll see how you can override that down the line but for now that's just another way to do it now perhaps the better if slightly cryptic way to do this or just the increasingly common way is probably this third version which looks a little weird too and probably the weirdness jumps out we've automatic we've suddenly introduced these like Curly braces which I promised were mostly gone and they are but inside of this string here I've done a curly brace which might mean what just intuitively here's sort of an example of how you learn a new language just kind of infer from Context how python probably works what might this mean yeah yeah so this is an indication because the curly braces because this is the way python was designed that we want to plug in the value of answer not literally a n s w e r and the fancy word here is that the answer variable will be interpolated that is substituted with its actual value but but but and this is actually weird looking this was introduced a few years ago to python what else did I have to change to make these curly braces work apparently yeah yeah there's this weird F and so it's sort of like part of print F but now it's inside the curly it's inside the parenthesis there this is just the way python designed it so a few years ago when they introduced what are called format strings or F strings you literally prefix your quoted string with the uh letter F and then you can use trickery like this like putting curly braces so that the value will be substituted automatically if you forget the F you're going to literally see hello comma curly brace answer close curly brace if you add the F it's indeed interpolated the value is plugged in all right questions on how we can just say hello to the world via python in this case yeah if you do this without the without the F if you omit the F you will literally see h-e-l-l-o comma curly brace a n s w e r close curly brace so in fact let's do this let me go back to vs code here quickly I've still got my file called hello.pi open and let me go ahead and change this ever so slightly so I'm going to go ahead and uh let's say from cs50 import get string and that's just the new syntax I propose using to import a function from someone else's Library I'm going to now go ahead and ask the question uh let's go ahead and use get string storing the result and answer so get string quote unquote what's your name question mark and then on this line I'm going to deliberately make a mistake here exactly to your question let me just say hello comma answer and just this now even though answer is a variable Python's not going to be so presumptuous as to just plug in the value of a variable called answer what it's going to do of course is if I type in my name whoops I type too fast let me go ahead and rerun that again if I run python of hello.pi type in my name and hit enter I get hello comma answer well let me do one better let me apply these curly braces as before let me re-run pythonofhello.pi what's your name David and here's again the answer to your question now we get literally the curly braces so the fix here ultimately is just going to be to add the F there rerun my program again with DAV ID and now hello comma David so this is admittedly a little more cryptic than the ones with the Plus or the comma but this is just increasingly common why because you can read it left to right it's nice and convenient it's less cryptic than the percent s's so it's sort of a new and improved version if you will of printf in C based on Decades of experience of programmers doing things like this questions on printing in this way we're now on our way to programming in Python anything all right well what more can we do with this language here well let me propose that we consider that we have for instance a few other features that we can add to the mix as well namely let's say some data types as well so let me flip over here to back to the slides and there's different data types in python as we'll soon see but they're not as explicit as we already saw by using a string from get string you don't have to explicitly State what it is but you solve or call and see all of these various data types and then in Python kind of nicely enough this list is about to get shorter and so here is our list in C here is an abbreviated list in Python so we're still going to have strings but they're going to be more succinctly called stirs now Str we're still going to have ints for integers we're still going to have floats for floating Point values we're even going to have bools for true and false but what's missing now from the list is long and floats and why is that or rather long and double we'll recall that in C those used more bits well in Python the smaller data types previously int and Float themselves just use more bits for you and so you don't need to distinguish between small and large you just use one data type and the language gives you a bigger range than before it turns out though there's going to be some other features as well of python these data types one of which will be called range another of which will be list So Gone will be arrays we'll actually use something literally called a list Tuple sort of like X Y pairs for coordinates and things like that addict for dictionaries so we'll have built-in capabilities for storing keys and values we'll see and even a set sort of mathematically a set is like a collection of values but it automatically gets rid of duplicates for you so all of these things we could absolutely Implement in C if we wanted and indeed in problem set five you've been implementing your very own spell checker using some form of hash table well it turns out that in Python you can solve those same problems but perhaps a little more readily in fact let me go back over here to vs code and let me propose that I do the following let me go ahead and create a file called dictionary dot Pi let me propose that I try to implement say problem set five our spell checker and python instead of c and Achieve ultimately the same kind of behavior whereby I'll be able to spell check a whole bunch of words so this is jumping the gun a little bit because you're about to see syntax will revisit over the course of today but for now I've got a new file called dictionary.pi and let me begin to create uh some placeholders for functions we'll see in just a bit that in Python you can define a function called check and that check function can take a word as its input and I'll come back to this in just a moment in Python I can define a second function like load which itself will take a whole dictionary just like in problem set 5 and I'll go ahead and come back to the implementation of this meanwhile we might similarly Implement a function called size which takes no arguments but ultimately it's going to return the size of my dictionary of words and then lastly for consistency with problem set five we might Define an unload function whose purpose in life is to free any memory that you've been using just to give it back to the computer now odds are whether you're still working on speller or half finished speller like you wrote a decent amount of lines of code and indeed it's been by design a challenge but one of the reasons for these higher level languages like python is that you can stand on the shoulders of programmers before you and solve very common problems much more quickly so that you can focus on building your new app or your web application or your own project to solve problems of interest to you so at the risk of crushing some Spirits let me propose that in Python if you want a dictionary for something like a spell checker well that's fine go ahead and give yourself a variable like words to store all of those words and just assign it equal to a dictionary or dict for short in Python that will give you a hash table now it turns out in speller recall you don't need to worry about words and definitions it's just about spell checking the words so strictly speaking we don't need keys and values we just need keys so I'm going to save myself a few more keystrokes by just saying that technically in Python using a set suffices again a set is just a collection of values with no duplicates but they don't necessarily have keys and values it's just one or the other but now that I have on line one I claim the equivalent in Python of a hash table I can actually do something like this here's how I might implement the check function in Python if the word passed into this function is in my variable called words well return true else go ahead and return false done and wait you're thinking if anything at all maybe we want to handle lower case instead of just uppercase and lowercase well you know what in Python if you want to force a whole word to lower case you don't have to iterate over it with a loop you don't have to use any of that c type functions or anything just say word dot lower and that will convert the whole thing to lowercase for parity with the dictionary all right how about something like the load function in Python well in Python you can open files just like in C for instance in Python I might do open the dictionary argument in read mode just like f open in Python I might do something like this for each line in that file let me go ahead and add to my words variable that line and then let me go ahead and close that file and I think I'm done I'm just going to go ahead and return true just because I think I'm already done now here too I could nitpick a little bit technically if I'm reading in every line from the file every line in the dictionary ends with technically a backslash n but there's an easy way to get rid of that just like you might in C with an alternative syntax what I'm actually going to do is this let me grab from the current line the current word by stripping off with reverse strip our strip a function we'll again see that just gets rid of the trailing new line the backslash n at the end of that line and what I really want to do then is add this word to that dictionary meanwhile if I want to figure out what the size is of my dictionary well and see you're probably writing code to iterate over all of those lines and you're just going to count them up using a variable not so in Python you can just return the length of those words and better still in Python you don't have to manage your own memory no more malloc no more free no more manual thinking about memory the language just deals with all of that for you so you know what it suffices for me to just return true and claim that unloading is done for me and that's it again whether you're in the middle of or already finished this might perhaps adjust some frustration but also Enlightenment in this in that this is why higher level languages exist you can build on top of the same principles the same ideas with which you've been dealing struggling even this past week but you can now express yourself all the more succinctly like this one line implements a hash table for you and all of this now just uses that hash table in a simpler way any questions now on this keeping in mind that the point nonetheless of speller and P said five is to understand what's really going on underneath the hood and better still to notice this this might seem all rather amazing but let me go ahead and do this I've actually got a couple of versions of speller written here and I've got a version written in C that I won't show the source code for but I'm going to go ahead and make that version of speller in C and I'm going to go ahead here and let's say split my window here for just a moment and I'm going to go into a python version of speller really that I just wrote and on the left hand side here let me go ahead and run speller the version I compiled in C using a big text like the Sherlock Holmes text which is a whole lot of words in it and on the right hand side let me run python of speller.pi which is a separate file I wrote in advance just like we give you speller.c and I'll similarly run this on the Sherlock Holmes text and I'm going to do my best to hit enter on the left and the right of my screen at the same time but we should see hopefully the same list of misspelled words and the timings thereof so here we go on the right here we go on the left all right sort of a race to see which one wins here C is on the left python is on the right okay interesting hopefully Python's close behind note that some of this is internet delay and so it might not necessarily be a crazy number of seconds but the system is indeed using if we measure at a low level how much time the CPU spent executing my code C took a total of 1.64 seconds that was pretty fast even though it took a moment more for all of the bytes to come over the Internet the python version though took what 2.44 seconds so what might be an inference be I mean one maybe I'm just better at programming in c than I am in Python which is probably not true but what else might you infer from this example should we maybe give up on python stick with c no so where what might be going on here like why is the python version that I claim is correct and I think the numbers all line up just not the times where is the trade-off here well here again is sort of this design trade-off yeah yeah exactly in order to save the human programmer time there's a lot more features built into python more functions more automatic management of memory and so forth and you have to pay a price like someone else's code is doing all of that work for you but if they were in some number of lines of code those are just more lines of code that need to be executed for you whereas here the computer is at the risk of oversimplifying only running my lines of code so there's just less overhead and so this is a Perpetual trade-off typically when using a more user-friendly and more modern language one of the prices you might pay is performance now there's a lot of smart computer scientists in the world though trying to push back on those same trade-offs and so these interpreters like the command I wrote python technically can especially if you run a program again and again they can actually sort of secretly behind the scenes compile your code for you down to zeros and ones and then the second the third the fourth time you run that program it might very well be faster so this is a bit of a head fake here in that I'm running them once and only one months but we could give benefit over time if we kept running the python version again and again and perhaps fine-tune the performance but in general there's going to be this trade-off now would you rather spend the 60 seconds I wrote implementing a spell checker or this six hour 16 hours you might be or have spent implementing the same and C you know probably not for productivity's sake this is why we have these additional languages just for fun let me flip over to another screen here and open up a version of python that's actually on my in just a second on my own uh Mac instead of the cloud so that I can actually do something with Graphics so here I just have a black and white terminal window on my very own Mac and I've pre-installed python just like we've done so for vs code in the cloud for you notice that I've got this uh photo of uh perhaps one of your favorite TV shows here with the cast of The Office notice all of the faces in this image here and let me propose that we try to find one face in the crowd sort of CSI style whereby we want to find perhaps the Scranton Strangler so to speak and so here is an example of this this guy's face now how do we go about finding this specific face in the crowd well our human eyes obviously can pluck them out especially if you're familiar with the show but let me go ahead and do this instead let me go ahead and propose that we run code that I already wrote in advance here this is a Python program with more lines of code that we won't dwell on for today but it's meant to motivate what we can do from a pillow Library implying a python image Library I want to import some type of information call some type of some feature called image so that I can manipulate images not unlike our own problem set for and this is kind of powerful in Python you can just import face recognition s a library that someone else wrote from there I'm going to create a variable called image I'm going to use this face recognitions libraries load image file function it's a little verbose but it's similar in spirit to F open and I'm going to open office.jpg I'm going to then declare a second variable called face locations plural because what I'm expecting to get back per the documentation for this library is a list of all of the faces locations that are detected all right then I'm going to iterate over each of those faces using a for Loop that we'll see in more detail I'm going to then infer with the top right bottom and left Corners are of that face and then what I'm going to do here is show that face alone if I've detected the face in question so let me go ahead here and run detect dot pi and we'll see not just the one face we're looking for but if I run python of detect.pi it's going to do all the analysis I'll see a big opening here now of all of the faces that were detected in this here program okay some better than others I guess if you zoom in on catching someone typical Angela if you now want to Now find that one face I think we need to train the software a bit more so let me actually open up a second program called recognize that's got more going on but let me with a wave of a hand point out that I'm now loading not only the office.jpg but also toby.jpg to sort of train the algorithm to find that specific face and so now if I run this second version recognize.pi with python of recognize.pi hold my breath for just a moment it's an analyzing presumably all of the faces you see the same original photo but do you see one such face highlighted here this version of the code found Toby highlighted him with the screen and voila we have face recognition so for better for worse this is what's happening increasingly societally nowadays and honestly even though I didn't write the code live because it's a good dozen or more lines of code it's not terribly many and literally all the authorities all we have to do is import face recognition and voila you have access like these Technologies are here already but let's consider for just a moment how did we find Toby like how might that Library even though we're not going to look at its implementation details how does it find Toby and distinguish him from all of these other faces in the crowd what might it be doing intuitively think back even to pset four like what you yourselves have access to data wise yeah yeah exactly and to summarize for for camera here do we have trained the software if you will by giving it a photo of Toby's face by so by looking for the same or really similar pixels especially if it's a slightly different image of Toby we can perhaps identify him in the crowd and what really is a human face well at the end of the day the computer only knows it as a pattern of bits or really at a higher level a pattern of pixels so maybe a human face is perhaps best defined in general as like two eyes and a nose and a mouth that even though all of us look similar structurally odds are the measurement between the eyes and the nose and the width of the mouth the skin tone and all of these other physical characteristics are patterns that software could perhaps detect and then look sort of statistically through the image looking for the closest possible match to these various measurement shapes colors and sizes and the like and indeed that might be the intuition but what's powerful here again is just how easy and readily available this technology now is all right so with that said let's propose to consider what more we can do with python itself get back to the fundamentals so that you yourselves can start to implement something along those same lines so besides having access to things like a get string function the cs50 library provides a few other things as well namely in C we had these but in Python we're going to have fewer in Python our library short term is going to give you not only get string but also get in and get float why it's actually just kind of annoying as we'll soon see to get back an integer or float from a user and just make sure that it's an INT and a float and not like a word like cat or dog or some string that's not actually a number well we can import not just the specific function get string but we can actually import all of these functions one at a time like this as we'll soon see or you can even in Python import specific functions from a file one of you asked a while back when you import when you include something like cs50.h or standard io.h you're actually getting all of the code in that file which potentially can add bulk to your own program or time in this case when you import specific functions from python you can be a little more narrowly precise as to what it is you want to have access to all right so with that said let's go ahead and see what conditionals look like in Python so in the left hand side again here we'll see scratch and here for instance was just kind of a contrived example asking if x is less than y then say x is less than y in C it looked like this in Python now it's going to look like this instead and here's before in C and here's after and just to call out a few of the obvious differences what has changed in Python for conditionals it would seem sort of what's the difference yeah yeah so there's no more curly braces and indeed you don't use those what appears to be taking their place if you might infer what seems to have taken their place what do you think so the colon at the start of this line here but also even more important now is this indentation below it so some of you and we know this from Office hours have a habit of like uh indenting everything on the left right and it's just kind of this crazy mess to look at frustrating for you shortly but C and clang is pretty tolerant when it comes to things like white space in a program python uh-uh they realized years ago that let's help humans help themselves and just require standard indentation so the four spaces would be the norm here but because it's indented below that colon that indeed indicates that this now is part of that condition something else has gone missing versus C in this conditional what else is a little simplified you yeah so no more parentheses you can still use them especially when you need to logically to do order of operations like in math but in this case if you just want to ask a simple question like if x less than y you can just do it like that how about when you have an if else well this is almost the same here with these same changes in C this looked like this and it's starting to get a bit bulky at least if we use our curly braces in this way in Python we can tighten things up further even though strictly speaking in C you don't always need the curly braces but here gone are the parentheses again gone are the curly braces indentation is consistent and we've just added another keyword else with a colon but no more semicolons as well how about something larger like this and if else if else this one's a little curious but in C it looked like this if else if else in Python it now looks like this and there's perhaps one curiosity here that honestly all these years later I still can't remember how to spell it half the time what's weird about this what do you spot as different uh yeah over here yeah instead of else if it's l if why apparently else space f was just too many key strokes for humans to type so they condensed it into this way probably means it's a little more distinguishable too for the computer between the if and the else too but just something to remember now it's indeed L if and not else if all right so what about variables in Python I've used a couple of them already but let's cut let's um distill exactly how you define uh and declare these things as well so in scratch if we wanted to create a variable called counter and set it equal initially to zero we would do something like this specify that it's an INT use the assignment operator and the thought with a semicolon in Python it's just simpler you name the variable you use the assignment operator as before you set it equal to some value and that's it you don't mention the type you don't mention the semicolon or anything more what if you want to change a variable like counter by one that is incremented by one you have a few different ways here in C we saw syntax like this where you can say counter equals counter plus one which again feels like a logical how can counter equal counter plus one but again we read this code really right to left updating its value by one in Python it's almost the same you just get rid of the semicolon so that logic is there but recalling C we could do something slightly different that we can also do in Python in Python you can also more succinctly do this plus equals and then whatever number you want to add or you can even change it to subtract if you prefer sadly gone is something you've probably typed a whole lot what was the other way you can add one plus plus is no more sadly in Python just too many ways to do the same thing so they got rid of it in favor of just the syntax here so keep that in mind as well what about loops when you want to do something in Python again and again well in scratch in week zero here's how we meowed three times specifically in C we had a couple of ways of doing this this was like the more mechanical approach where you create a variable called I you set it equal to zero you then do while I is less than three the following and then you yourself increment I again and again mechanical in the sense that like you have to implement all of these gears and make them turn yourself but this was a correct way to do that in Python we can still achieve the same idea but we don't need the int keyword we don't need any of the semicolons we don't need the parentheses we don't need the curly braces we can't use the plus plus so maybe that's a minor step backwards if you're a fan but otherwise the code the logic is exactly the same but there's other ways to achieve this same idea recall that in C we could also do this you could use a for Loop which it does exactly the same thing both are correct both are arguably well designed it's kind of to each their own when it comes to choosing between these in Python though we're gonna have to think through how to do this so you don't do the same for loop as in C the closest I could come up with is this where you say 4 I or whatever variable you want to do the counting in literally the preposition and then you use square brackets here and we've used square brackets before in the context of like arrays and things like that and the 0 1 2 looks like an array in some sense even though we've also seen arrays with curly braces but these square brackets for now denote and list python does not have arrays an array is that contiguous chunk of memory back to back to back that you have to resize somehow by moving things around in memory as per two weeks ago in Python though you can just create a list like this using square brackets and better still as we'll see you can add or even remove things from that list down the road this though is not going to be very well designed this will work this will iterate in Python three times but what might rub you the wrong way about this design even if you've never seen python before how does this example not end well yeah yeah like if you're making a large list you have to type out each one of these numbers like comma three comma four comma five comma dot dot 50 comma dot dot 500 like surely that's not the best solution to have all of these numbers on the code on the screen rapping endlessly on the screen so in Python another way to do this would be to use a function called range which technically is a data type unto itself and this returns to you as many values as you ask for it range takes some other arguments as well but the simplest use case here is if you want back the number 0 1 and 2 a total of three values you say hey python please give me a range of three values and by default they start at zero on up but this is more efficient than it would be to hard code the entire list at once and the best metaphor I could come up with is something like this like here for instance is a deck of cards this is sort of normal human size and there's presumably 52 cards here so writing out 0 through 51 on code would be a little ridiculous for the reasons you know it would just be very unwieldy and ugly and rapping and all of that it would be the physical it would be the virtual equivalent of me like handing you all of these cards at once to just deal with and right you know they're not that big but like it's a lot of cards to hold on to it requires a lot of memory or physical storage if you will what range does metaphorically is if you ask me for three cards I hand you them one at a time like this so that at any point in time you only have one number in the computer's memory until you're handed the next the alternative the previous version would be to hand me all three cards at once or all 52 cards at once but in this case range is just way more efficient you can do range of a thousand that's not going to give you a list of a thousand values all at once it's going to give you a thousand values one at a time reducing memory significantly in the computer itself all right so besides this what about doing something forever in scratch well we could do this literally with a forever block which didn't quite exist in C in C we had a hack it together by saying while true because true is by definition t-r-u-e always true so this just in deliberately induces an infinite Loop for us in Python the logic is going to be almost the same and infinite Loops in Python tend to actually be even more common because you can always break out of them as you could in C in Python it looks like this and this is slightly more subtle but gone are the curly braces gone are the parentheses but ever so slight difference two a capital T for true and it's going to be a capital f for false stupid little differences eventually you're going to miss type one or the other but these are the kinds of things to keep an eye out and to start recognizing in your mind's eye when you read code questions now on any of these building blocks in the for Loop was I re uh it was set to zero on the first iteration then one on the next then two on the third and the same thing for range it just doesn't use up as much memory all at once other questions now on any of these building blocks of python all right well let's go ahead and build something a little more than hello let let me propose that over here we Implement maybe the the simplest of calculators here so let me go back to vs code here open my terminal uh window and open up say a file called calculator dot pi and in calculator.pi we'll have an opportunity to explore some of these building blocks but we'll allow things to escalate pretty quickly to more interesting examples so that we can do the same thing ultimately as well and in fact let me go ahead and do this moreover I've brought some code with me in advance for instance something called calculator 0.c from the first week of c and let me go ahead and split my window here in fact so that I can now do something like uh this let me move this over here here calculator.pi so now I have on the left of my screen calculator dot C or calculator 0.c because that's the first version I made in calculator.pi on the right let me go ahead and Implement really the same idea here so on the right hand side the analog of including cs50.h would be from cs50 import get int if I want to indeed use this function now I'm going to go ahead and give myself a variable X without defining its type I'm going to use this get int function and I'm going to prompt the user for X just like in C I'm then going to go ahead and prompt the user for another int like y here just like in C and at the very end I'm going to go ahead and do print X Plus y and that's it now granted I have some comments in my C version of the code just to remind you of what each line is doing but I've still distilled this into like six lines or really four if I get rid of the blank line so it's already perhaps a bit tighter here but there's also it's tighter because something really important historically is missing what did I seem to Omit altogether that we haven't really highlighted yet yeah yeah the main function is gone and in fact maybe you took for granted that it just worked a moment ago when I wrote hello but I didn't have a main function in hello either and this too is a feature of python and a lot of other languages as well instead of having to adhere to these long-standing Traditions if you just want to write code and get something done fine just write code and get something done without necessarily all of the same boilerplate so whatever is in your python file left indented if you will by default is just going to be the code that The Interpreter runs top to bottom left to right well let me go ahead now and run code like this let me go ahead and open map back up my terminal window run python of calculator.pi and I'll do X is one y is two and as you might expect it gives me three slight aesthetic bug I put my space in the wrong place here so that's a newbie mistake let me fix that aesthetically let me rerun python of calculator.pi type in one type in two and voila there is now my same version again but let me propose now that we get rid of this training wheel we don't want to keep taking one step forward and then two steps back by adding these training wheels so let me instead do this in my version of calculator.pi suppose that we take away already the training wheel that is the cs50 library here and let me instead then use just Python's built-in function called input which literally does just that it gets input from the user and it stores it as before in X and Y so this is not cs50 specific this is real world Python Programming well let me go ahead and run again python of calculator.pi and of course if x is 1 and Y is 2 X Plus y should of course still be three hmm it's apparently 12 according to python until cs50's Library gets involved but does anyone want to infer what's just went wrong yeah exactly the input function by Design always returns a string of text after all that's what the human typed in and even though yes I typed the number keys on the keyboard it's still coming back as all text now maybe we should use like a get int function well that doesn't exist in Python all you can do is get textual input a string from the user but we can convert one to the other and so a fix for this so that we don't accidentally concatenate that is join X Plus y together would be to do something like this let me go back to my python code here and whereas in C we could previously do type casting we could convert one type to another that generally wasn't the case when you were doing something complex like a string to an inch you could do a Char to an INT and vice versa but for a string recall there was a special function in the c-type library called a to I like ASCII to integer that's the closest analog here and in fact the way to do this in Python would be to use a function called int which indeed is the name of the data type too even though I have not yet had to type it and I can convert the output of the input function automatically from a string immediately to an INT and now if I go back to my terminal window we run python of calculator.pi with 1 and 2 for X and Y now I'm back in business so that then is for instance what the cs50 library does if temporarily this week is it just deals with the conversion for you and in fact bad things could happen if I type the wrong thing like dog or cat instead of a number but we'll cross that bridge in just a moment as well all right what if we do something slightly different now with our calculator instead of just addition let me go ahead and do how about uh instead of addition let's do division instead so Z equals x divided by y thereby giving me a third variable Z let me go ahead and run python of calculator.pi again I'll type in one I'll type in three this time and what program what problem do you think we're about to see or is it gone what happened when I did this in C albeit with some slightly more cryptic syntax when I divided one number like one one divided by three anyone recall yeah yeah so it would round down to the nearest integer whereby you experience truncation so if you take an integer like one you divide it by another integer like three that technically should be 0.33333 infinitely long but in C recall you truncate the value if you divide an inch by an INT you get back an inch which means you get only the integer part which was the zero now python actually handles this for us and avoids the truncation but it leaves us still with one other problem here which is going to be for instance not necessarily visible at a glance this looks correct this has solved the problem in C so truncation does not happen the integers are automatically converted to a float a floating point value but what other problem did we trip over back in weak one what else got a little dicey when dealing with simple arithmetic anyone recall well the syntax in Python's a little different but let me go ahead and do this it turns out in Python if you want to see more significant digits than what I'm seeing hereby to default which is a dozen or so let me go ahead and print out Z as follows let me first print out a format string because I want to format Z in an interesting way and notice this would have no effect on the difference this is just a format string that for no compelling reason at the moment is interpolating z in those curly braces using an F string or format string if I run this again with one and three we'll see indeed the exact same thing but when you use an F string you indeed have the ability to format that string more precisely just like with percent F in Python you could start to fine tune how many significant digits you see in pi in C rather in Python you can do the same but the syntax is a little different if you want the computer to interpolate Z and show you 50 significant digits that is 50 numbers after the decimal point syntax is similar to C but it's a little different you literally put a colon after the variable's name dot 50 means show me the decimal point and then 50 digits to the right and the F just indicates please treat this as a floating point value so now if I rerun python of calculator.pi divide 1 by 3 unfortunately python has not solved all of the world's problems for us this again was an example of floating point in Precision so that problem is still latent so just because the world has advanced doesn't necessarily mean that all of our problems from C have gone away there are solutions using third-party libraries for scientific calculations and the like but out of the box floating point and precision is still an issue meanwhile there was one other problem in C that we ran into involving numbers and that was this integer overflow recall that an integer in C only took up what like 32 bits typically which meant you could count as high as 4 billion or maybe if you're doing positive and negatives as high as 2 billion after which weird things would happen the number would go to zero or negative or just it would overflow or wrap back around well wonderfully in Python they did at least address this whereby you can count as high as you want and python will just use more and more and more and more bits and bytes to store really big numbers so integer overflow is not a thing with that said python is limited to how many digits it will show you on the screen at once as a string but mathematically your math will be correct now so we've taken a couple steps forward One Step sideways but indeed we've solved some of our problems here all right questions now on any of these examples thus far question all right well how about uh how about another problem that we encountered in C let's be revisit here in python as well so let me go ahead and on the left hand side here let me open up a file called say compare let's see uh how about a file called compare 3.c on the left and let me go ahead and create a new file on the right called compare.pi because recall that bad things happened when we needed to compare two values in C so on the left here is a reminder of what we once didn't see whereby if we want to compare values we can get an INT and C stored in x a get int in C stored in y we then have our familiar conditional logic here just printing out if x is less than y or not well we can certainly do the same thing ultimately in Python by using some fairly familiar syntax and let's just demonstrate this one quickly let me go over here too I'll do from cs50 import get int even though I could do this instead with the input function itself x equals get int and I'll prompt the user for that y equals get int and I'll prompt the user for that after that recall that I can say without parentheses if x is less than y then print out without the f x is less than y then I can go ahead and say else if x is greater than y I can print out uh quote unquote X is greater than y if you'd like to interject now what did I screw up anyway yeah LF right so L if L if x is greater than y else this part's the same print X is equal to Y so there's not all that much new there's no New Logic going on here but at least syntactically it's a little cleaner indeed this program's only 11 lines long albeit without any comments let me go ahead and run python of compare.pi let's see is one less than two indeed let's run it again is 2 less than one no it's greater than and let's lastly type in one and one twice X is equal to one so we've got a pretty side by side one-to-one conversion here let's do something a little more interesting than in C how about I open instead something where we actually compared for a purpose so if I open up from thus uh from earlier in the course how about uh agree.c which prompt the user to agree to something or not and let me code up a new version here called agree dot pi and I'll do this on the right hand side with the greed up Pi but on green.c on the left notice that this is why we did this sort of yes no thing in C we compared c a character equal to single quotes y or equal to single quotes little Y and then same thing for n now in Python this one's actually going to be a little bit different here let me go ahead and in the python version of this let me do something like this uh we'll use get string uh well actually no we'll just use input in this case so let's do s equals input and we'll ask the user the same thing do you agree question mark then let's go ahead and say if s equals equals how about y how do I do this well a few things turns out I'm going to do this s equals equals little y then I'm going to go ahead and print out agreed and L if s equals equals capital N or S equals equals lowercase n I'm going to go ahead and print out not agreed and I claim for the moment that this is identical now to the program on the right the program on the left in C but what's different so we're still doing the same kind of logic these equal equals for comparing for equality but notice that nicely enough python got rid of the two vertical bars and it's just literally the word or if you recall seeing Ampersand Ampersand to express a logical and in C you can just write literally the word and and so here's a hint of why pythons tends to be pretty popular people just like that it's a little closer to English there's a little less of the cryptic syntax here now this is correct as this code will now work but I've also used double quotes instead of single quotes and I also omitted a few minutes ago for my list of data types in Python the word Char in Python there are no chars there are no individual characters if you want to manipulate an individual character you use a string that is to say a stir of size one now in Python you can use single quotes or double quotes I'm deliberately using double quotes everywhere just for consistency with how we treat strings in C it's pretty kind common though to use single quotes instead if only because on most keyboards you don't have to hold the shift key anymore I mean humans have really started to optimize just how quickly they want to be able to code so using a single quote tends to be pretty popular in Python and other languages as well they are fundamentally the same uh single or double unlike in C where they have meaning so this is correct I claim and in fact let me run this real quick I'll open up my terminal window here let me get rid of the version and see and run python of agree.pi and I'll type in y okay I'll run it again and type in little Y and I'll stipulate it's going to work for no as well but this isn't necessarily the only way we can do this there are other ways to implement the same idea and in fact I can go about doing this instead let me go back up to my code here and we saw a hint of this earlier we know that lists exist in Python and you can create them just by using square brackets so what if I simplify the code a little bit and just say if s is in the following list of values capital y or lowercase y it's not all that different logically but it's a little tighter it's a little more compact so L if s is in capital N or lowercase n i can express that same idea too so here again it's just getting a little more pleasant to write code there's less like hitting of the keyboard you can express yourself a little more succinctly and using the keyword in Python will figure out how to search the entire list for whatever the value of s is and if it finds it it will return true automatically else it will return false so if I run agree dot Pi again and type in capital y or lowercase y that still now works well I can type in tighten this up further if I want to add more features well what if I want to support not just wah Big Y and little y but how about yes or yes or in case the user's yelling or you know someone who doesn't really isn't good with caps lock types in yes wait a minute but it could be weird like do we want to support this or this I mean this this gets really tedious quickly combinatorically if you consider all of these possible permutations what would be smarter than doing something like this if you want to just be able to tolerate yes in any form of capitalization like logically what would be nice maybe whatever to all lower controls as well exactly super common Paradigm why don't we just force the user's input to all lowercase or all uppercase doesn't matter so long as we're self-consistent and just compare against all uppercase or all lowercase and that will get rid of all of the possible permutations otherwise now in C we might have done something like this we might have simplified this whole list and just said let's say uh we'll do how about lowercase so y or yes and we'll just leave it at that but we need to force now s to lowercase well in C we would have used the C type Library we would have done like two lower and called that function passing it in although not really because in C type those operate on individual characters or chars not whole strings we actually didn't see a function that could convert a whole string in C to lowercase but in Python we're going to benefit from some other feature as well it turns out that python supports what's called object oriented programming and we're only going to scratch the surface of this and C is 50 but if you take a higher level course in programming or CS you'll explore this as a different Paradigm up until now in C we've been focusing on what's called really procedural programming you write procedures you write functions top to bottom left to right and when you want to change some value we were in the habit of using a procedure that is a function you would pass something like a variable into a function like two upper or two lower and it would do its thing and hand you back a value well it turns out that it would be nicer programming wise if some data types just had built-in functionality like why do we have our variables over here and all of our helper functions like two upper and two lower over here such that we constantly have to pass one into the other it would be nice to sort of bake into our data types some built-in functionality so that you can change variables using their own default built-in functionality and so object oriented programming otherwise known as oop is a technique whereby certain types of value like a string AKA stir not only have properties inside of them attributes just like a struct in C your data can also have functions built into them as well so whereas in C which is not object oriented you have structs and structs can only store data like a name and a number when implementing a person in Python you can for instance have not just a structure otherwise known as a class storing a name and a number you can have a function like call that person or email that person or actual verbs or actions associated with that piece of data now in the context of strings it turns out that strings come with a lot of useful functionality and in fact at this URL here which is in docs.python.org which is the official documentation for python you'll see a whole list of methods that is functions that come with strings that you can actually use to modify their values and what I mean by this is the following if we go through the documentation poke around it turns out out that strings come with a function called Lower and if you want to use that function you just have to use slightly different syntax than in C you do not do two lower and you do not say as I just did lower because this function is built into s itself and just like in C when you want to go inside of a variable like a structure and access a piece of data inside of it like name or number when you also have functions built into data types AKA methods a method is just a function that is built into a piece of data you can do s dot lower open paren close paren in this case and I can do this down here as well if s dot lower in quote unquote n or no the whole thing I can force this whole thing to lowercase so the only difference here now is an object-oriented programming instead of constantly passing a value into a function you just access a function that's inside of the value it just works because of how the language itself is defined and the only way you know whether these functions exist is the documentation a Class A book a website or the like questions now on this technique all right I claim this is correct now even though you've never programmed most of you in Python before not super well designed there's a subtle inefficiency now on lines three and five together what's dumb about how I've used lower might you think yeah yeah if you're going to use the same function twice and ask the same question expecting the same answer why are you calling the function itself twice maybe we should just store the resultant variable so we could do this in a couple of different ways we for instance could go up here and create another variable called T and set that equal to s dot lower and then we could just change this to be T here but honestly I don't think we technically need another variable altogether here I could just do something like this let's change the value of s to be the lowercase version thereof and so now I can quite simply refer to S again and again like this reusing that same value now to be sure I have now just lost the user's original input and if I care about that if they typed in all caps I have no idea anymore so maybe I do want to use a separate variable altogether but a takeaway here too is that strings in Python are technically what we'll call immutable that is they cannot be changed this was not true in C once we gave you arrays in week two or memory in week four you could go to town under string and change any of the characters you want upper casing lowercasing changing it shortening it and so forth but in this case this returns a copy of s forced to lowercase it doesn't change the original string that is the memory the bytes in the computer's memory when you assign it back to S you're essentially forgetting about the old version of s but because python does memory management for you there's no malloc there's no free python automatically frees up the original bytes like y-e-s and hands them back to the operating system for you all right questions now on this technique questions on this in general I'll call out the python documentation we'll start to be your friend because in class we'll only scratch the surface with some of these things but in docs.python.org for instance there's a whole reference of all of the built-in functions that come with the language as well as for instance those with a string all right well let me go ahead and before we take a break let's go ahead and create something a little familiar too based on our weeks here in C let me propose that we revisit those examples in the involving some meows so for instance when we had our cat meow back in the first week and then second in C we did something that was a little stupid at first whereby we created a file as I'll do here this time called meow.pi and if I want a cat to meow three times I could run it once like this a little copy paste and now python of meow.pi and I'm done now we've visited this example like two times at least now in scratching and C it's correct I'll stipulate but what's obviously poorly designed what's the fault here yeah it should just be a loop right like why type it three times literally copying and pasting is almost always a bad thing except in C when you have the function prototypes that you need to borrow but in this case this is just inefficient so what could we do better here in Python well in Python we could probably change this in a few different ways we could borrow some of the syntax we proposed in slide form earlier like give me a variable called I set it to zero no semicolon while I is less than three if I want to do this three times I can go ahead and print out meow and then I can do I plus equals one and I think this would do the trick python of meow.pi and we're back in business already well if I wanted to change this to a for Loop well in Python it would be a little tighter but this would not be the best approach so for I in 0 1 2 I could just do print meow like this and that too would get the job done but to my uh to our discussion earlier this would get stupid pretty quickly if you had to keep enumerating all of these values like what did we introduce instead the the range function exactly so that hands me back way more efficiently just the values I want indeed one at a time so even this if I run it a third a third or fourth time we've got the same result but now let's transition to where we went with this back in the day how can we start to modularize this like just like it would be nice I claimed if MIT had given us a meow function wouldn't it be nice if like python had given us a meow function maybe less compelling in Python but how can I build my own function well I did this briefly with the spell checker earlier but let me go ahead and propose that we could Implement now our own version of this in python as follows let me go ahead and start fresh here and use the keyword def so this did not exist in C you had the return value the function name the arguments in Python you literally say def to define a function you give it a name like meow and now I'm going to go ahead and in this function just print out meow and this lets me change it to anything else I want in the future but for now it's an abstract action and in fact I can move it out of sight out of mind just going to hit enter a bunch of times to pretend like now it exists but I don't care how it is implemented and up here now I can do something like this for I in range of three let me go ahead and not print meow anymore let me just call meow and tightening up my code further but I think let's see python of meow.pi this is I think going to be the first time it does not work correctly okay so here we have sadly our first python error and let's see the syntax is going to be different from C or clang's output traceback is like the term of art here this is like a trace back of all of the lines of code that were just executed or really functions you called the file name is uninteresting this is like my code space specifically but the file name is important here meow.pi line two is the issue okay I didn't get very far before I screwed up and then there's a name error and you'll see in Python there's typically these capitalized uh keywords that hint at what the issue is it's something related to names of variables meow is not defined all right you're programming python for the first time you've screwed up you're following some online tutorial you're seeing this reason through it like why might meow not be defined what can we fur infer about python how to troubleshoot logically maybe is it because meow is defined after you know as smart as python seems to be Visa VC they have some similar design characteristics so let's try that so let me scroll all the way back down to where I moved this earlier let me uh get rid of it way down there I'll copy it to my clipboard and let me just kind of hack something together let me just put it up here and let's see if this works so now let me clear my terminal run python of meow.pi okay we're back in business so that was actually really good intuition good debugging technique to sort of reason through it now this is kind of contradicting what I claimed back in week one which was that you know the main part of your program ideally should just be at the top of the file like don't make me look for it it's not a huge deal with like a four-line program but if you've got 40 lines 400 lines you don't want like the juice juicy part of your program to be way down here and all of these functions way up here so it would be nice maybe if we actually have a main function and so it actually turns out to be a convention in Python to define a main function it's not a special function that's automatically called like in C but humans realized you know what that was a pretty useful feature let me Define a function called main let me indent these lines underneath it let me practice what I'm preaching which is put the main code at the top of the file and wonderfully in Python now you do not need prototypes there's none of that hackish copying and pasting of the return type the name and the arguments to a function like we needed in C this is now okay instead except for one Minor Detail let me go ahead and run python of meow.pi hopefully now I've solved this problem by having a main function but now nothing has happened all right even if you've never programmed in Python before What might explain this Behavior and how do I fix again when you're off in the real world learning some new language all you have is deductive logic to debug yeah right so the solution to be clear in C was that we had to put the Prototype up here otherwise we'd get an error message in this case I'm actually not getting an error message and indeed I'll claim that you don't need the prototypes in Python just not necessary because that was annoying if nothing else but what else might explain yeah and back yeah maybe you have to call Main itself if Maine is not some special status in Python maybe just because it exists isn't enough and indeed if you want to call Maine the new convention is actually going to be as the very last line of your program typically to literally call Maine it's a little stupid stupid looking but you know they made a design decision and this is how now we work around it python of meow.pai now we're back in business but now logically why does this work the way it does well in this case top to bottom line one is telling python to define a function called Main and then Define it as follows lines two and three but it's not calling main yet line six is telling python how to define a function called meow but it's not calling these lines yet now on line 10 you're telling python call Main and at that point python has been trained if you will to know what Maine is on line one to know what meow is on line six and so it's now perfectly okay for Maine to be above meow because you never called them yet you defined defined and then you called and that's the logic behind this any questions now on the structure of this technique here now let's do one more then recall that the last thing we did in scratch and in Python scratch and then see was to actually parameterize uh these same functions so suppose that you don't want Maine to be responsible for the loop here you instead want to very simply do something like meow three times and be done with it well in Python it's going to be similar in spirit to see but again we don't need to keep mentioning data types if you want meow to take some argument like a number n you can just specify n as the name of that argument or you could call it anything else of course that you want you don't have to specify int or anything else in your code now inside of meow you can do something like 4 I in let's say I definitely now can't do this because like that would be weird to start the list and end it with n so if I can come back over here what's the solution how can I do something n times yeah using range so range is nice because I can pass in now this variable n and now I can meow whoops now I can print out quote unquote meow so it's almost the same as in scratch almost the same as in C but it's a little simpler and if now I run meow dot Pi I'll have the ability now to do this here as well all right questions on any of this right now we're sort of like taking the stroll through week one we're going to momentarily escalate things to look not only at some of these Basics but also other features like we saw with face recognition with the speller or the like um because of how many of us are here we have a huge amount of candy out in the lobby so why don't we go ahead and take a 10 minute break and we come back we'll do even fancier more powerful things with python in 10. all right so we are back among our goals now are to introduce a few more building blocks so that we can solve more interesting problems at the end much like those that we began with you'll recall from a few weeks ago we played with this sort of two-dimensional Super Mario World and we tried to print a vertical column of like three or more bricks well let me propose that we use this as an opportunity to now Tinker with some of Python's more uh useful more user-friendly functionality as well so let me code a file called mario.pi and let's just print out like that the equivalent of that vertical column so it's of height three each one is a hash so let's do 4i in range of three and initially and let's just print out a single hash and I think now python of mario.pi voila we're in business printing out just that same pyramid there or just that same column there what if though we want to print a column of like some variable height where the user tells us how tall they want it to be well let me go up here for instance and instead how about we'll use um let's do this how about uh from cs50 import how about the get in function as before so it will deal with making sure the user gives us an integer and now in the past whenever we wanted to get a number from a user we've actually followed a certain Paradigm in fact if I open up here for instance how about Mario in how about Mario 1.c from a while back you might recall that we had code like this and we specifically used the do while loop and see whenever we want to like get something from the user maybe again and again and again until they cooperate at which point we finally break out of the loop so it turns out python does have while Loops does have for Loops does not have do while loops and yet pretty much any time you've gotten user input you've probably used this Paradigm so it turns out that the python equivalent of this is to do similar in spirit but using only a while loop and a common Paradigm in python as I alluded earlier is to actually deliberately induce an infinite Loop while true capital T and then do what you want to do like get an INT from the user and prompt them for the height for instance in question and then if you're sure that the user has given you what you want like n is greater than zero which is what I want in this case because I want a positive integer otherwise there's nothing to print you literally just break out of the loop and so we could actually use this technique in C it's just not really done one in C you could absolutely and C have done a while true loop with the parentheses lowercase true you could break out of it and so forth but in Python this is like the python way and this is actually a term of art this way in Python is pythonic like this is the way everyone does it quote unquote doesn't mean you have to but that's sort of the way like the cool python programmers would Implement an idea like this trying to do something again and again and again until the user actually cooperates but all we've done is take away the do while loop but still logically we can implement the same idea now below this let me go ahead and just print out for I in range of n this time because I want it to be variable and not three I can go ahead and print out the hash let me go ahead and get rid of the C version here open my terminal window and I'll run again python of mario.pi I'll type in three and I get back those three hashes but if I instead type in four I now get four hashes instead so the takeaway here is quite simply that this would be the way for instance to actually get back a value in Python that is consistent with some parameter like greater than zero how about this let's actually practice what we preached a moment ago with our meowing examples and kind of factoring all this out let me go ahead and Define a main function as before let me go ahead and assume for the moment that a get height function exists which is not a thing in Python I'm going to invent it in just a moment and now I'm going to go ahead and do something like this for I in the range of that height well let's go ahead and print out those hashes so I'm assuming that get height exists let me go ahead and Implement that abstraction so Define a function now called get height it's not going to take any arguments in this design while true so I can go ahead and do the same thing as before assign a variable n the return value of get int prompting the user for that height and then if n is greater than zero I can go ahead and break but if I break here I logically just like in C end up executing below the loop in question but there's nothing there but if I want get height to return the height what should I type here on line 14 logically what do I want to return to be clear yeah so I actually want to return n and here's another curiosity of python Visa BC there doesn't seem to be an issue of scope anymore right in C it was super important to not only declare your variables with the data types you also have to be mindful of like where they exist inside of those curly braces in Python it turns out you can be a little looser with things for better for worse and so on line 11 if I create a variable called n it exists on line 11 12 and even 13 outside of the while loop so to be clear in C with a while loop we would have ordinarily had not a colon we would have had the curly brace like here and over here and a week ago I would have claimed that in C N does not exist outside of the while loop by nature of those curly braces even though the curly braces are gone python actually allows you to use a variable anytime after you have assigned it a value so slightly more powerful as such however I can tighten this up a little bit logically and this is true in C I don't really need to break out of the loop by using break recall that or know that I can actually once I'm ready to go I can just return the value I care about even inside of the loop and that will have the side effect of breaking me out of the loop and also breaking me out of and returning from the entire function so nothing too new here in terms of C versus python except for this issue of scope and I indeed returned and at the bottom there just to make clear that n would still exist so either of those are correct now I just have a Python program that I think is going to allow me to implement the same Mario idea so let's run python of mario.pi and okay so nothing happened uh python of mario.pi what did I do wrong yeah I have to call Maine so at the bottom of my code I have to call Main here and this is a stylistic detail that's been subtle generally speaking when you are writing in Python there's not a cs50 style guide per se there's actually a python style guide that most people adhere to it's a and in this case double blank lines between functions is the norm I'm doing that deliberately although it might otherwise not be obvious but now that I've called main on line 16 let's run mario.pi once more aha now we get there now we see it type in three and I'm back in business printing out the values there yeah sure why do I need the if condition at all why can't I just return n here as by doing return n or if I really want to be succinct I could technically just do this the only reason I added the if condition is because if the user types in negative 1 negative two I wanted to prompt them again and again that's all but that would be totally acceptable too if you were okay with that result instead well let me do one other thing here to point out why we are using get int so frequently this new training wheel albeit temporarily so let me go back to the way it was a moment ago and let me propose now to take away get int I claimed earlier that if you're not using get int you can just use the input function itself from python but that always returns a string or a stir and so recall that you have to pass the output of the input function to an INT either on the same line or if you prefer on another line instead but it turns out what I didn't do was show you what happens if you don't cooperate with the user with the program so if I run python of mario.pi now works great even without the get int function and I can do it with four still works great but let me clear my terminal and be difficult now as the user and type in cat for the height instead enter now we see one of those Trace backs again this one is different this isn't a name error but apparently a value error and if I kind of ignore the stuff I don't understand I can see invalid literal for INT with base 10 cat that's a super cryptic way of saying that cat is not a number in decimal notation and so I would seem to have to somehow handle this case and if you want to be more Curious you'll see that this is indeed a trace back and C tends to do this too or the debugger would do this for you too you can see all of the functions that have been called to get you to this point so apparently my problem is initially in line 14 but line 14 if I keep scrolling is uninteresting it's main but line 14 leads me to execute line two which is indeed in Main that leads me to execute line 9 which is in get height and so okay here's the issue so the closest line number to the error message is the one that probably reveals the most line nine is where my issue is so I can't just blindly ask the user for input and then convert it to an INT if they're not going to give me an INT now how do we deal with this well back in problem set two you might recall validating that the user typed in a number and using a for Loop and the like well it turns out there's a better way to do this in Python and the semantics are kind of there if you want to try to convert something for a number to a number that might not actually be a number turns out Python and certain other languages literally have a keyword called try and if only this existed for the past few weeks I know but like you can try to do the following with your code what do I want to try to do well I want to try to execute those few lines except if there's an error so I can say except if there's a value error specifically the one I screwed up and created a moment ago and if there is a value error I can print out an informative message to the user like not an integer or anything else and what's happening here now is literally this operative word try the pro python is going to try to get input and try to convert it to an end and it's going to try to check if it's greater than zero and then try to return it alt why all of three of those lines are inside of indented underneath the try block except if something goes wrong specifically a value error happens then it prints this but it doesn't return anything and because I'm in a loop that means it's going to do it again and again and again until the human actually cooperates and gives me an actual number and so this too is what the world would call pythonic in Python you don't necessarily rigorously try to validate the user's input make sure they haven't screwed up you honestly take a more laxativesical approach and just try to do something but catch an error if it happens so catch is also a term of art even though it's not a keyword here except if something happens you handle it so you try and you handle it you sort of best effort programming if you will but this is baked into the mind mindset of the Python Programming community so now if I do python of mario.pi and I cooperate works great as before try and succeed three Works four works if though I try and fail by typing in cat it doesn't crash per se it doesn't show me an error it shows me something more user friendly like not an integer and then I can try again with dog not an integer I can try again with five and now it works so we won't generally have you write much in the way of these try except blocks only because they get a little sophisticated quickly but that is to reveal what the get in function is doing this is why we give you the training wheel so that when you want to get an INT you don't have to jump through all these annoying Hoops to do so but that's all the library is really doing for you is just try and accept you won't be left with any training wheels ultimately questions now on getting inputs and trying in this way anything at all yeah it say that oh you could you put the condition outside of the try block short answer yes and in fact I struggled with this last night when tweaking this example to show the simplest version I will disclaim that really I should only be trying literally to do the The Fragile part and then down here I should be really doing what you're proposing which is do the condition out here the problem is though that logically this gets messy quickly right because except if there's a value error I want to print out not an integer I can't compare n against zero then because n doesn't exist because there was an error so it turns out and I'll show you this this is now the advanced version of python there's actually an else keyword you can use in Python that does not accompany if or L if it accompanies try and accept which I think is weirdly confusing a different word would have been better but if you really prefer I could have done this instead and this is one of these design things where like reasonable people will disagree generally speaking you should only try to do the one line that might very well fail but honestly this looks kind of stupid now I just unnecessarily complicated and so my own preference was actually the original which was yeah I'm trying a few extra lines that really aren't going to fail mathematically but it's just tighter it's cleaner this way and here's again the sort of like you know arguments you'll start to make yourself as you get more comfortable with programming you'll have an opinion you'll disagree with someone and so long as you can back your argument up pretty reasonable probably all right so how about we now take away some piece of magic that's been here for a while let me go ahead and delete all of this here and let me propose that we revisit uh not that vertical column and the exceptions that might result from getting input but these like horizontal question marks that we saw a while ago so I want all of those question marks on the same line and yet I worry we're about to see a challenge here because print up until now has been putting new lines everywhere automatically even without those backslash ends well let me propose that we do this for I in the range of four if I want four question marks let me just print four question marks unfortunately I don't think this is correct yet let me run python of mario.pi and of course this gives me a column instead of the row of question marks that I want so how do we do this well it turns out if you read the documentation for the print function it turns out that print not surprisingly perhaps takes a lot of different arguments as well and in fact if you go to the documentation for it you'll see that it takes not just positional arguments that is from left to right separated by commas turns out python has supports a fancier feature with arguments where you can pass the names of arguments to functions too so what do I mean by this if I go back to vs code here and I've read the documentation it turns out that yes as before you can pass multiple arguments to python like this like hello comma David comma Malin that will just automatically concatenate all three of those positional arguments together they're positional in the sense that they literally flow from left to right separated by commas but if you don't want to just pass in values like that you want to actually print out as I did before a question mark but you want to override the default behavior of print by changing the line ending you can actually do this you can use the name of an argument that you know exists from the documentation and set it equal to some alternative value and in fact even though this looks cryptic this is how I would override the end of each line to be quote unquote that is nothing because if you read the documentation the default value for this end argument does someone want to guess is is backslash n so if you read the documentation you'll see that backslash n is the implied default for this end argument and so if you want to change it you just say end equals something else and so here I can change it to nothing and now rerun python of mario.pi and now they're all on the same line now it looks a little stupid because I made that sort of week one mistake where I still need to move the cursor to the next line that's just a different problem I'm just going to go over here and print nothing I don't even need to print backslash n because if print automatically gives you a backslash n just call print with nothing and you'll get that for free so let me rerun python of mario.pi and now it looks a little prettier at the prompt and to be super clear as to what's going on suppose I want to sort of make an exclamation here I could change the backslash and default to like an exclamation point Just for kicks and if I run python of mario.pi again now I get this sort of you know exclamation with question marks and exclamation points as well so that's all that's going on here and this is what's called a named argument it literally has a name that you can specify when calling it in and it's different from positional and that you're literally using the name let me propose something else though and this is why people kind of like python there's just kind of cool ways to do things that's kind of a you know it's a three-line verbose way of printing out four question marks you know I could certainly take the you know shortcut and just do this but that's not really that interesting for anyone especially if I want to do it a variable number of times but python does let you do this if you want to multiply a character some number of times not only can you use Plus for concatenation you can use star or an asterisk for multiplication if you will that is concatenation again and again and again so if I just print out quote unquote question mark times four that's actually going to be the tightest way the most succinct way I can print four question marks instead and if I don't use four I use n where I get n from the user bang like now I've gotten rid of the for Loop entirely and I'm using the the star operator to manipulate it instead and to be super clear here insofar as python does not have my lock or free or memory management that you have to do guess what python also doesn't have anything on your minds in the past couple of weeks doesn't have pointers yeah so python does not have pointers which just means that all of that happens for you automatically underneath the hood Again by way of code that someone else wrote how about one more throwback with Mario we've talked about in week one this sort of two-dimensional structure where it's like I claim like three by three a grid of bricks if you will well how can we do this in Python we can do this in a couple of ways now let me go back to my mario.pi and let me do something like for I in range of we'll just do three even though I know now I could use get int or I could use input and int and if I want to do something two-dimensionally just like in C you can Nest your for Loop so maybe I could do 4J in range of three and then in here I could print out a hash symbol and then let's see if that gives me nine total so if I've got a nested Loop like this python of mario.pi hopefully gives me a grid no it gave me a column of nine why logically even though I've got my row and my columns yeah yeah the line ending so in my row I can't let print just keep adding new line adding new line so I just have to override this here and let me not screw up like before let me print one at the end of the whole row just to move the cursor down and I think now together now we've got our three by three of course we could tighten this up further like if I don't like the nested loop I probably could go in here and just print out for instance a a brick times three or I could change the three to a variable if I've gotten it from the user so I can tighten this up further so again just different ways to solve the same problem and again sort of evidence of why a lot of people like python there's just some more pleasant ways to solve problems without getting into the weeds constantly of doing things like with um for loops and while Loops endlessly all right well how about some other building blocks lists are going to be so incredibly useful in Python just as arrays were in C but arrays are annoying because you have to manage the memory yourself you have to know in advance how big they are or you have to use pointers and malloc or re-alloc to resize them like oh my God like the past two weeks have been painful in that sense but python does this all for free for you in fact there's a whole bunch of functions that come with python that involve lists and they'll allow us ultimately to do things again and again and again uh with uh within the same data structure and for instance we'll be able to get the length of a list you don't have to remember it yourself in a variable you can just ask python how many elements are in this list and with this I think we can solve some some old problems too so let me go back here to vs code let me close Mario and give us a new program called scores dot pi and rather than show the C and the python now let's just focus on Python and in scores.c way back when we just averaged like three test scores or something like that 72 73 and 33 a few weeks ago so if I want to create a list in this python version of 72 73 33 I just use my square bracket notation C let you use curly braces if you know the values and in advance but Python's just this and now if I want to compute the average in pi in C recall I did something with a loop I added all the values together I then divided by the total number of values just like you would in grade school and that gave me the average well python comes with a lot of super handy functions not just length but others as well and so in fact if you want to compute the average you can take the sum of all of those scores and divide it by the length of all of those scores so python comes with length comes with sum you can just pass in a whole list of any size and let it deal with that problem for you so if I want to now print out this average I can print out average colon and then I'll plug in my average string for a variable for interpolation let me make this an F string so that it gets formatted and let me just run python of scores dot pi and there's my average it's sort of rounding weird because we're still vulnerable to some floating point in Precision but at least I didn't need loops and I didn't have to write all this darn code just to do do something that you know excel in Google spreadsheets can just do like that well python is closer to those kinds of tools but more powerful in that you can manipulate the data yourself how about though if I want to get a bunch of scores manually from the user and then sum them together well let's combine a few ideas here how about this first let me go ahead and import um the cs50 live get in function from the csrt library just so we don't have to deal with try and accept or all of that and let me go ahead and give myself an empty list and this is powerful in Python C there's really there's no point to an empty array because if you create an empty array with square bracket notation like it's not useful for anything but in Python you can create it empty because python will grow and shrink the list for you automatically as you add things to it so if I want to get three scores from the user I could do something like this for I and range of three and then I can grab a variable called score or anything I could call get int prompt the human for the score that they want to type in and then once they do I can do this thinking back to our object oriented programming capability now I could do scores dot append and I can append that score to it and you would only know this from having read the documentation heard it in class in a book or whatnot but it turns out that just like strings have functions like lower built into them lists have functions like append built into them that just literally appends to the end of the list for you and python will grow or Shrink it as needed no more malloc or Cal or realic or the like so this just appends to the scores array the scores list that score and then again and again and again so the array starts at sorry the list starts at size 0 then grows to one then two then three without you having to do anything else and so now down here I can compute an average with the sum of those scores divided by the length of the total number of scores and to be clear length is the total number of elements in the list doesn't matter how big the values themselves are now I can go ahead and print out an F string with something like average colon average and curly braces and if I run python of scores dot Pi I'll type in just for the sake of discussion the three values I still get the same answer but that would have been painful to do in C and less you can committed in advance to a fixed size array which we already decided weeks ago was annoying or you grew it dynamically using malloc or realloc or the like all right so what else can I do well there's some nice things you might as well know exist um instead of scores.apen you can do slight fanciness like this like if you want to append something to a list you can actually do plus equals and then put that thing in a temporary list of its own and just use what is essentially concatenation but not concatenation of strings but concatenation of lists so this new line six appends to the scores list this tiny little list I'm temporarily creating with just the current new score so just another piece of syntax that's worth seeing that allows you to do something like that as well all right well how about we go back to strings for a moment and all these examples as always are on the course's website afterward suppose we want to do something like converting characters to uppercase well to be clear I could do something like this let me create a program called uppercase.pi let me prompt the user for a before string as by using the input function or get string which is almost the same and I'll prompt the user for a string beforehand then let me go ahead and print out uh how about the keyword after and then end the new line with nothing just so that I can see before on one line and after on the next line and then let me do this and here's where python gets Pleasant two with loops for C in before print C Dot Upper end equals quote unquote and then I'll print this here all right that was fast but let's try to infer what's going on so line one just gets input from the user stores it in a variable called before line two literally just prints after but doesn't move the new line to the cursor to the next line what it then does is this and in C this was a little more annoying you needed a for loop with I you needed array in notation with the square brackets but python if you say four variable in string so for c for character in string python is going to automatically assign C to the first letter that the user types in then on the next iteration the second letter the third letter and the fourth so you don't need any square bracket notation you just use C and python will do it for you and just hand you back one at a time each of the letters that the user has typed in so if I go back over here and I run for instance python of uppercase.pi and I'll type in how about uh David in all lower case and hit enter you'll now see that it's all uppercase instead by iterating over it indeed one character at a time but we already know thanks to object oriented programming strings themselves have the functionality built in to not just uppercase single characters but the whole string so honestly this was a bit of a silly exercise I don't need to use a loop anymore like in C and so some of the habits you've only just developed in recent weeks it's time to start breaking them when they're not necessary I can create a variable called after set it equal to before Dot Upper which indeed exists just like dot lower exists and then what I can go ahead and print out is for instance let's get rid of this print line here and do it at the end after and print the value of that variable so now if I rerun uppercase.pi type in David in all lower case I can just uppercase the whole thing all at once because again in C in Python you don't have to operate on characters individually questions on any of these tricks up until now now all right how about a few other techniques that we saw and see that we'll bring back now in Python so it turns out in Python there are other libraries you can use too that unlock even more functionality so in C if you wanted command line arguments you just change the pro the signature for main to be void instead of void to be int rgc comma string ARG V Open brackets for an array or Char star eventually well it turns out in Python that if you want to access command line arguments it's a little simpler but they're tucked away in a library otherwise known as a module called CIS the sys or system module now this is similar in spirit to the cs50 library and it's got a bunch of functionality built in but this one comes with python itself so if I want to create a program like greet dot Pi in vs code here let me go ahead and do this from the sys Library let's import ARG V and that's just a thing that exists it's not built into main because there is no main per se anymore so it's tucked away in that library and now I can do something like this if the length of ARG V equals equals two well let's go ahead and print out something friendly like hello comma ARG V bracket one and then close quotes else if the length of ARG V is not equal to two let's just go ahead and print out hello world now at a glance this might look a little cryptic but it's identical to what we did a few weeks ago when I run this python of greet.pi with no arguments it just says hello world but if I instead add a command line argument like my first name and hit enter now the length of ARG V is no longer one it's going to be 2 and so it prints out hello David instead so the takeaway here is that whereas in C ARG V technically contained the name of your program like dot slash hello or dot slash greet and then everything the human typed Python's a little different in that because we're using The Interpreter in this way Technically when you run python of greek.pi the length of RV is only one it contains only Greek dot Pi so the name of the file it does not unnecessarily contain python itself because what's the point of that being there omnipresently it does contain the number of words that the human typed after python itself so ARG V is length one here ARG V is length two here and that's why when it did equal to I saw hello David instead of the default hello world so same ability to access command line arguments add these kinds of inputs to your functions but you have to unlock it by way of using argv instead in this way if you want to see all of the words you could do something like this it just as if we combine ideas here for I in range of how about length of arc V then I can do this print ARG V bracket I alright a little cryptic but line three is just a for Loop iterating over the range of length of ARG V so if the human types in two words the length of arc V will be two so this is just a way of saying iterate over all of the words in ARG V printing them one at a time so python of Greek dot Pi enter just prints out the name of the program python of greek.pi with David prints out greet dot pi and then David I can keep running it though with more words and they'll each get printed one at a time but what's nice too about Python and this is the point of this exercise honestly this looks pretty cryptic this is not very pleasant to look at if you just want to iterate over every word in a list which ARG V is watch what I can do I can do for ARG or any variable name in ARG V let me just now print out that argument I could keep calling it I but I seems weird when it's not a number so I'm changing to ARG as a word instead if I now do python of greet dot Pi it does this if I do python of greek.pi David it does that again David Malin it does that again so this is again why Python's just very appealing you want to do something this many times iterate over a list just say it and it reads a little more like English and there's even other fanciness too if I may it's a little stupid that I keep seeing the name of the program greet.pi so I it'd be nice if I could remove that python also supports what are called slices of arrays oh sorry slices of lists even though I get the terminology confused if ARG V is a list then it's going to print out everything in it but if I want a slice of it that starts at location one all the way to the end you can use this funky syntax in between the square brackets which we've not seen yet that's going to start at item one and go all the way to the end and so this is a nice clever way of slicing off if you will the very first element because now when I run greet.pi David Malin I should only see David and Malin if I only want one element I could do one to two if I want all of them I could do 0 onward I could give myself just two of one of them in this way so you can play with the start value and the N value in this way to sort of slice and dice these lists in different ways that would have been a pain in C just because we didn't really have the built-in support for manipulating arrays as cleanly as this all right just so you've seen it too oh this one is less exciting to see live if I go ahead and create a quick program here it turns out there's something else in the sys Library the ability to exit programs either exiting with status code one or zero as we've been doing anytime something goes right or wrong so for instance Let Me Whip up a quick program that just says if the length of sys.org V uh does not equal 2 then let's yell at the user and say you're missing a command line argument otherwise command line argument and let's then return CIS dot exit one else let's go ahead and logically just say print a formatted string that says hello as before sys.org V1 now things look different all of a sudden but I'm doing something deliberately first let's see what this does so on line one I'm importing not ARG V specifically I'm importing the whole sys library and we'll see why in a second well it turns out that this RV the sys library has not only the argue list it also has a function called exit which I'd like to be able to use as well so it turns out that if you import a whole library in this way that's fine but you have to refer to the things inside of it by using that same library's name and a DOT to sort of namespace it so to speak so here I'm just saying if the user types in does not type in two words yell at them with missing command line argument and then exit with one just like in C when you do exit one just means something went wrong otherwise print out hello to to this and this is starting to look cryptic but it's just a combination of ideas the curly braces means interpolate this value plug it in here cis.org V is just the verbose way of saying go into the sys library and get the ARG variable therein and bracket one of course just like arrays and C is just the second element at the prompt so when I run this version now python of exit.pi with no arguments I get yelled at in this way if however I type in two arguments total the name of the file and my own name now I get greeted with hello David and it's the same idea before this was a very low level technique but same thing here if you do Echo dollar sign question mark enter you'll see the exit code of your program so if I do this incorrectly again let me rerun it without my name enter I get yelled at but if I do Echo dollar sign question mark there's the secret one that's returned again just to show you parity with C in this case questions now on any of these techniques here no all right how about something that's a little more powerful too we spend so much time in week zero and one doing searching and then eventually sorting in week three well it turns out python can help with some of this too let me go ahead and create a program called names.pi that's just going to be an opportunity to maybe search over a whole bunch of names let me go ahead and import sys and then just so I have access to exit and let me go ahead and create a variable called names that's going to be a list with a whole bunch of names uh how about Here Charlie and Fred and George and Ginny and Percy and lastly Ron so a whole bunch of names here and you know it'd be a little Annoying to implement code that iterates over that from left to right and see searching for one of those names in fact what name well let's go ahead and ask the user to input the name that they want to search for so that we can sell them if the name is there or not and we could do this similar to C in Python doing something like this so for n in names where n is just a variable to iterate over each name if how about the name I'm looking for equals the current name in the list aka-n well let's print out something friendly like found and then let's do sys.exit zero to indicate that we found whoever that is otherwise if we get all the way to the bottom here outside of this Loop let's just print not found because if we haven't exited yet and then let's just exit with one just to be clear I can continue importing all of CIS or I could do from sys import exit and then I could get rid of sys dot everywhere else but you know sometimes it's helpful to know exactly where functions came from so this too is just a matter of style in this case all right so let's go ahead and run this python of names.pi and let's look for like Ron all the way at the end you know all right he's found and let's search for someone outside of the family here like Hermione not found okay so it seems to be working in this way but I've essentially implemented what algorithm what algorithm would this seem to be per line seven and eight to nine and ten yeah so it's just linear search it's a loop even though the syntax a little more succinct today and it's just iterating over the whole thing well honestly we've seen an even more terse way to do this in Python and this again is what makes it a more pleasant language sometimes why don't I just do this instead of iterating one at a time why don't I just say this let me go ahead and change my condition to just be How about if the name we're looking for is in the names list we're done we found it use the in preposition that we've seen a couple of times now that itself asks the question is something in something else and python will take care of linear search for us and it's going to work exactly the same if I do Mython of names.pi search for run it's still going to find him and it's still going to do it linearly in this case but I don't have to write all of the lower level code myself in this case questions now on any of this code's just getting shorter and shorter now what about uh let's see what else might we have here how about this it turns out let's go ahead and Implement that phone book that we started metaphorically with in the beginning of the course let's code up a program called phonebook dot pi and in this case let's go ahead and let's create a dictionary this time recall that a dictionary is a little something that implements something like this like a two column table that's got keys and values words and definitions names and numbers and let's focus on the last of those names and numbers in this case well I claimed earlier that python has built-in support for dictionaries dict objects that you can create with one line I didn't need it for speller because a set is sufficient when you only want one of the keys or the values not both but now I want some names and numbers so it turns out in Python you can create an empty dictionary by saying dict open parenthesis close and that just gives you essentially a chart that looks like this with nothing in it or there's more succinct syntax you can alternatively do uh this with two curly braces instead and in fact I've been using a shortcut all this time when I had a list earlier where my variable uh was called scores and I did this that was actually the shorthand version of this hey python give me an empty list so there's different Syntax for achieving the same goal in this case if I want a dictionary for people I can either do this or more commonly just two curly braces like that all right well what do I want to put in this well let me actually put some things in this and I'm going to just move my closed curly brace to a new line if I want to implement this idea of keys and values the way you do this in Python is key colon value comma key colon value so you'd implement it more in code so for instance if I want Carter to be the first key in my phone book and I want his number to be plus one six one seven four nine five one thousand I can put that as the corresponding value the colon is in between both are strings or stir so I've quoted both deliberately if I want to add myself I can put a comma and then just to keep things pretty I'm moving the cursor to the next line but that's not strictly required aesthetically it's just good style and here I might do plus one nine four nine four six eight uh two seven five zero and now I have a dictionary that essentially has two rows here David Carter and his number and David and his number as well and if I kept adding to this this call this chart would just get longer and longer suppose I want to search for one of our numbers well let's prompt the user for the name for whose number you want to search by getting string or you know what we don't need the cs50 library let's just use input and prompt the user for a name and now we can use this super ter syntax and just say if name in people print the formatted string number colon and here we can do this people bracket name okay so this is getting kind of cool kind of quickly kind of confusingly so let me run this python a phone book dot Pi let's type in Carter and indeed I see his number let's run it again with David and I see my number here so what's going on well it turns out that a dictionary is very similar in spirit to a list it's actually very similar in spirit to an array in C but instead of being limited to keys that are numbers like bracket zero bracket one bracket two you can actually use words and that's all I'm doing here on line eight if I want to check for the name Carter which is currently in this variable called name I can index into my people dictionary using not a number but using literally a string the name Carter or David or anything else to make this clear too notice that I'm at the moment using this format string which is adding some undo complexity but I could clarify this perhaps further as this I could give myself another variable called number set it equal to the people dictionary indexing into it using the current name and now I can shorten this to make it clear that all I'm doing is printing the value of that and in fact I can do this even more cryptically if I this would be weird to do but if I only ever want to show David's phone number and never Carter's I can literally quote unquote index into the people dictionary because now when I run this even if I type Carter I'm going to get back my number instead but that's all that's happening if I undo that because that's now a bug but I index into it using the value of name dictionaries are just so wonderfully convenient because now you can associate anything with anything else but not using numbers but entire keywords instead so here's how if in speller we gave you not just words but hundreds of thousands of definitions as well you could essentially store them as this and then when the human wants to look up a definition in a proper dictionary not just for spell checking you could index into the dictionary using square brackets and get back the definition in English as well questions on this yeah a really good question so how to summarize how is python finding that name within that dictionary this is where honestly speller and pset 5 is what Python's all about so you have struggled are struggling with implementing your own spell checker and implementing your own hash table and recall that per last week the goal of a hash table is to ideally get constant time access not something linear which is slow and even better than something uh logarithmic like log base 2 of n so Python and the really smart people who invented it they have written the code that does its best to give you constant time searches of dictionaries and they're not always going to succeed just as you and your own problem said probably going to have some collisions once in a while and start to have chains of linked lists of words but this is where again you defer to someone else someone's smarter than you someone with more time than you to solve these problems for you and if you read Python's documentation you'll see that it doesn't guarantee constant time but it's going to ideally optimize the data structure for you to get as fast as possible and of all of the data structures like a dictionary a hash table is really like the Swiss army knife of computing because it just lets you associate something with something else and you even though we keep focusing on names and numbers that's a really powerful thing because it's more powerful than lists and arrays which are only numbers and something else now you can have any sorts of relationships instead all right let me show a few other examples before we culminate with some more powerful techniques in pythons thanks to libraries how about this problem we encountered in week four which was this let me code up a program called again compare.pi here but this time compare two strings and not numbers so let me for instance do get one string from the user called s just for the sake of discussion let me get another string from the user called T so that we can actually do some comparison here and if s equals equals T let's go ahead and print out that they're the same else let's go ahead and print out that they're different so this is very similar to what we did in week four but in week four recall we did this specifically because we had encountered a problem for instance if I run whoops uh if I run what's going on uh come on oh the okay wow okay long day all right if I run the proper command python of compare.pi then let's go ahead and type in something like cat in all lowercase cats in all lower case and they're the same uh if though I do this again with dog and dog they're the same and of course cats and dogs they're different but does anyone recall from two weeks ago when I typed in my name twice both identically capitalized what did it say that they were in fact different and why was that like why were two strings in C different even though I typed literally the same thing two different places in memory so each string might look the same aesthetically but of course was stored elsewhere in memory and yet python appears to be using the equality operator equals equals like you and I would expect as humans actually comparing for us Char by Char in each of those strings for actual equality so this is a feature of python in that it's just easier to do and why well this derives from the reality that in Python there are no pointers anymore there's no underlying memory management it's not up to you now to worry about those lower level details the language itself takes care of that for you and so similarly if I do this and don't ask the user for two strings but just one and then I do something like this how about give myself a second variable T set it equal to s dot capitalize which note is not the same as upper capitalized by Design per Python's documentation will only capitalize the first letter for you I can now print out say two F strings here what the value of s is and then let me print out with another F string what the value of T is and recall that in C this was a problem because if you capitalize s and store it in t we accidentally capitalize both s and t but in this case in Python when I actually run this and type in cat in all lower case the original s is unchanged because when I use capitalize on line three this is indeed capitalizing s but it's returning a copy of the result it cannot change S itself because again for that technical term s is immutable strings once they exist cannot be changed themselves but you can return copies and modified mutated copies of those same strings so in short all of those headaches we encountered in week four are now solved really in the way you might expect and here's another one that we dwelled on in week four with the colored liquid in glasses let me code up a program called swap dot pi and in swap.pi let me set x equal to 1 y equal to two and then let me just print out an F string here so how about X is this comma Y is that and then let me do that twice just for the sake of demonstration and in here recall that we had to create a swap function but then we had to pass it in by reference with the Ampersand and like oh my God like that was kind of peak complexity and C well if you want to swap X and Y in Python you could do X comma y equals y comma X and now python of swap whoops python of swap dot pi and there we go all of that's handled for you it's sort of like a shell game without even a temporary variable in mind so so what more can we do here how about a few final building blocks and these related now to files from that week four suppose that I want to save some names and numbers in like a a CSV file comma separated values which is like a very lightweight spreadsheet well first let me create a phonebook.csv file that just has name comma number as like the first row there but after that I'm going to go ahead now and code up a phone book dot Pi program that actually allows me to add things to this phone book so let me split my screen here so that we can see the old and the new and down here in my code for phonebook.pi in this new and improved version I'm going to actually import a whole other Library this one called CSV and here too especially for people in data science and the like really like being in a manipulate files and data that might very well be stored in spreadsheets or csvs comma separated values which we saw briefly in week four in phonebook.pi then it suffices to just import CSV after reading the documentation therefore because this is going to give me functionality in code related to CSV files so here's how I might open a file in Python I literally call open it's not F open now it's just open and I open this file called phonebook.csv and just as in C I'm going to open it in append mode not right where it would change the whole thing I want to append new line at a time after this I want to get maybe how about a name from the user so let's prompt the user for some input for their name and then let's prompt the user for a number as well using input prompting for number all right and now this is a little cryptic and you'd only know this from the documentation but if you want to write line rows to a CSV file that you can then view in Excel or the like you can do this give me a variable called writer but I could call it anything I want let me use a CSV dot writer function that comes with this CSV Library passing in the file this is like saying hey python treat this open file as a CSV file so that things are separated with commas and nicely formatted in rows and columns now I'm going to do this use that writer to write a row well what do I want to write I want to write a short list namely the current name and the current number to that file but I don't want to use F printf and percent s and all of that stuff that we might have had in the past and now I just want to close the file let me reopen my terminal let me run python of phonebook.pi and let me type in how about David and then plus one nine four nine four six eight two seven five zero and hold crossing my fingers watching the actual CSV at top left my code has just added me to the file and if I were to run it again for instance with Carter and plus one six one seven four nine five one thousand crossing my fingers again we've updated the file and it turns out there's code now via which I can even read that file but I can first tighten this up just so you've seen it it turns out in Python it's so common to open files and close them you know humans make mistakes and they often forget to close files which might then end up using more memory than you intend so you can alternatively do this in Python so that you don't have to worry about closing files you can use this keyword instead you can say with the opening of this file as a variable called file do all of the following underneath so I'm indenting most of my code I'm using this new python specific keyword called with and this is just a matter of saying with the following opening of the file do those next four lines of code and then automatically close it for me at the end of the indentation it's a minor optimization but this again is sort of the pythonic way to do things instead how else might I do this too well it turns out that the code I've written here on line 9 especially is a little fragile right if any human opens this spreadsheet the CSV file in Excel Google spreadsheets Apple numbers and maybe like move the columns around just because maybe they're fussing they save it and they don't realize they've now changed my assumptions I don't want to necessarily write name and number always in that order because what if someone screws up and flips those two columns by literally dragging and dropping so it turns out that instead of using a list here we can use another feature of this Library as follows instead of using a writer there's something called a dictionary writer or dict writer that takes the same argument as input the file that's opened but now the one difference here is that you need to tell this dictionary writer that your field names are name and number and let me close the CSV here name and number are the names of the fields The Columns in this CSV file and when it comes time to write a new row the syntax here is going to be a little uglier but it's just a dictionary the name I want to write to the dictionary is going to be whatever name the human typed in the number that I want to write to the CSV file is going to be whatever the number the human typed in but what's different now about this code is by simply using a dictionary writer here instead of the generic writer now the columns can be in this order or this order or any order and the dictionary writer is going to figure out based on the first line of text in that CSV where to put name where to put number so if you flip them no big deal it's going to notice oh wait the columns changed and it's going to insert the columns correctly so just again another more powerful feature that lets you focus on lets you focus on real work as opposed to actually getting tied up in the weeds of writing code like this otherwise questions on this one as well but what we will do now is come full circle to some of the more sophisticated examples with which we began and I'm going to go back over to my own Mac laptop here where I've got my own terminal window up and running and I was just going to introduce a couple of final libraries that really speak to just how powerful python can be and how quickly you can get up and running to be fair can't necessarily do all of these things in the cloud like in code spaces because you need access to your own speakers or microphone or the like so that's why I'm doing it on my own Mac here but let me go ahead and open up a program called Speech dot pi and I'm not using vs code here I'm using a program called VI that's entirely terminal window based but it's going to allow me for instance to import the python text to speech version 3 Library I'm going to give myself a variable called engine that's going to be set equal to the python text to speech 3 live libraries init method which is just going to initialize this library that relates to text to speech I'm going to then use the engines say function to say something like how about hello comma world and then as my last line I'm going to say engine dot run and wait capitalized as such to tell my program now to run that speech and wait until it's done all right I'm going to save this file I'm going to run python of speech.pi and I'm going to cross my fingers as always and hello world all right so now I have a program that's actually synthesizing speech using a library like this how can I now modify this to be a little more interesting well how about this let me go ahead and prompt the user for their name like we've done several times here using Python's built-in name function and now let me go ahead and use a format string in conjunction with this Library interpolating the value of name there and at least if my name is somewhat phonetically pronounceable let's go ahead and run pythonofspeech.pi type in my name and hello David okay it's a sort of weird choice of inflection but we're starting to synthesize voice not unlike Siri or Google assistant or Alexa or the like now we can maybe do something a little more advanced too in addition to synthesizing speech in this way we could synthesize for instance an actual graphic let me go ahead now and do something like this let me create a program called QR dot Pi I'm going to go ahead and import a library called OS which gives you access to operating system related functionality in Python I'm going to import a library if pre-installed called QR code which is a two-dimensional barcode that you might have seen in the real world I'm going to go ahead and create an image variable using this QR code libraries make function which per its documentation takes a URL like one of cs50's own videos so we'll do this with YouTube slash x v f z j o five p g 0 so hopefully that's the right lecture and now we've got image.save which is going to allow me to create a file called qr.ping think back now on problem set four and how painful it was to save files we'll just use the save function now in Python and save this as a ping file portable Network graphic and then lastly let's go ahead and open uh the com with the command open QR dot ping on my Mac so that hopefully this just automatically opens all right I'm going to go ahead and just double check my syntax here so that I haven't made any mistakes I'm going to go ahead and run python of QR dot Pi enter that opens up this let me go ahead and zoom in if you've got a phone handy and you'd like to scan this code here whether in person or online I apologize you won't appreciate it amazing okay and lastly let me go back into our speech example here create a final ending here in our final moments and how about we just say something like this one cs50 like this let's go ahead here fix my capitalization just for tidiness get rid of the name and now with our final flourish and your introduction to python equipped here we go this was cs50 all right we'll see you next time [Applause] [Music] thank you

Original Description

*** This is CS50, Harvard University's introduction to the intellectual enterprises of computer science and the art of programming. *** TABLE OF CONTENTS 00:00:00 - Introduction 00:01:12 - Python 00:03:10 - Compilation, Interpretation 00:04:32 - Hello 00:15:09 - Types 00:16:51 - Speller 00:25:56 - Image Recognition 00:31:06 - CS50 library 00:32:22 - Conditionals 00:35:09 - Variables 00:36:33 - Loops 00:41:50 - Calculator 00:51:35 - Compare 00:59:31 - Object-Oriented Programming 01:05:20 - Meow 01:14:38 - Mario 01:35:45 - Scores 01:40:35 - Uppercase 01:43:57 - Greet 01:48:27 - Exit Status 01:51:02 - Search 01:54:15 - Phonebook 02:00:49 - Compare 02:04:11 - Swap 02:05:13 - CSV 02:11:01 - Speech *** 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/ Slack: https://cs50.edx.org/slack Snapchat: https://www.snapchat.com/add/cs50 SoundCloud: https://soundcloud.com/cs50 Stack Exchange: https://cs50.stackexchange.com/ TikTok: https://www.tiktok.com/@cs50 Twitter: https://twitter.com/cs50 YouTube: http://www.youtube.com/cs50 HOW TO FOLLOW DAVID J. MALAN Facebook: https://www.facebook.com/dmalan GitHub: https://github.com/dmalan Instagram: https://www.instagram.com/davidjmalan/ LinkedIn: https://www.linkedin.com/in/malan/ Quora
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 Hello, World: Hadi Partovi
Hello, World: Hadi Partovi
CS50
2 Content Distribution and Archival in a Digital Age
Content Distribution and Archival in a Digital Age
CS50
3 CS50 2014 - Week 1
CS50 2014 - Week 1
CS50
4 CS50 2014 - Week 3
CS50 2014 - Week 3
CS50
5 CS50 2014 - Week 0, continued
CS50 2014 - Week 0, continued
CS50
6 CS50 2014 - Week 4
CS50 2014 - Week 4
CS50
7 Week 3, continued
Week 3, continued
CS50
8 Quiz 0 Review
Quiz 0 Review
CS50
9 CS50 2014 - Week 3, continued
CS50 2014 - Week 3, continued
CS50
10 CS50 2014 - Week 7
CS50 2014 - Week 7
CS50
11 CS50 2014 - Week 7, continued
CS50 2014 - Week 7, continued
CS50
12 Breaking Through The (Google) Glass Ceiling by Christopher Bartholomew
Breaking Through The (Google) Glass Ceiling by Christopher Bartholomew
CS50
13 Introduction to Amazon Web Services by Leo Zhadanovsky
Introduction to Amazon Web Services by Leo Zhadanovsky
CS50
14 CS50 2014 - Week 9
CS50 2014 - Week 9
CS50
15 How to Build Innovative Technologies by Abby Fichtner
How to Build Innovative Technologies by Abby Fichtner
CS50
16 Light Your World (with Hue Bulbs) by Dan Bradley
Light Your World (with Hue Bulbs) by Dan Bradley
CS50
17 Building Dynamic Web Apps with Laravel by Eric Ouyang
Building Dynamic Web Apps with Laravel by Eric Ouyang
CS50
18 CS50 2014 - CS50 Lecture by Steve Ballmer
CS50 2014 - CS50 Lecture by Steve Ballmer
CS50
19 CS50 2014 - Week 10
CS50 2014 - Week 10
CS50
20 This is CS50 with Steve Ballmer?
This is CS50 with Steve Ballmer?
CS50
21 Meteor: a better way to build apps by Roger Zurawicki
Meteor: a better way to build apps by Roger Zurawicki
CS50
22 Data Analysis in R by Dustin Tran
Data Analysis in R by Dustin Tran
CS50
23 Data Visualization and D3 by David Chouinard
Data Visualization and D3 by David Chouinard
CS50
24 CS50 2014 - Week 6
CS50 2014 - Week 6
CS50
25 Build Tomorrow's Library by Jeffrey Licht
Build Tomorrow's Library by Jeffrey Licht
CS50
26 CS50 2014 - Week 9, continued
CS50 2014 - Week 9, continued
CS50
27 Essential Scale-Out Computing by James Cuff
Essential Scale-Out Computing by James Cuff
CS50
28 iOS App Development with Swift by Dan Armendariz
iOS App Development with Swift by Dan Armendariz
CS50
29 Sam Clark Leads Yale Students on Tour to CS50 at Harvard
Sam Clark Leads Yale Students on Tour to CS50 at Harvard
CS50
30 3D Modeling and Manufacture by Ansel Duff
3D Modeling and Manufacture by Ansel Duff
CS50
31 CS50 2014 - Week 5, continued
CS50 2014 - Week 5, continued
CS50
32 hello, world
hello, world
CS50
33 CS50 2014 - Deep Thoughts - Hash Table
CS50 2014 - Deep Thoughts - Hash Table
CS50
34 CS50 2014 - Deep Thoughts - Binary Tree
CS50 2014 - Deep Thoughts - Binary Tree
CS50
35 CS50 2014 - Deep Thoughts - Scratch
CS50 2014 - Deep Thoughts - Scratch
CS50
36 CS50 2014 - Deep Thoughts - MySQL
CS50 2014 - Deep Thoughts - MySQL
CS50
37 LaunchCode Visits CS50
LaunchCode Visits CS50
CS50
38 CS50 Live, Episode 100
CS50 Live, Episode 100
CS50
39 CS50 Field Trip to Google
CS50 Field Trip to Google
CS50
40 This is CS50 AP
This is CS50 AP
CS50
41 Week 4: Monday - CS50 2011 - Harvard University
Week 4: Monday - CS50 2011 - Harvard University
CS50
42 Week 2: Wednesday - CS50 2011 - Harvard University
Week 2: Wednesday - CS50 2011 - Harvard University
CS50
43 Week 1: Wednesday - CS50 2011 - Harvard University
Week 1: Wednesday - CS50 2011 - Harvard University
CS50
44 Week 11: Monday - CS50 2011 - Harvard University
Week 11: Monday - CS50 2011 - Harvard University
CS50
45 Week 3: Wednesday - CS50 2011 - Harvard University
Week 3: Wednesday - CS50 2011 - Harvard University
CS50
46 Week 12: Monday - CS50 2011 - Harvard University
Week 12: Monday - CS50 2011 - Harvard University
CS50
47 Week 1: Friday - CS50 2011 - Harvard University
Week 1: Friday - CS50 2011 - Harvard University
CS50
48 Week 3: Monday - CS50 2011 - Harvard University
Week 3: Monday - CS50 2011 - Harvard University
CS50
49 Week 10: Wednesday - CS50 2011 - Harvard University
Week 10: Wednesday - CS50 2011 - Harvard University
CS50
50 Week 2: Monday - CS50 2011 - Harvard University
Week 2: Monday - CS50 2011 - Harvard University
CS50
51 Week 9: Monday - CS50 2011 - Harvard University
Week 9: Monday - CS50 2011 - Harvard University
CS50
52 Week 7: Monday - CS50 2011 - Harvard University
Week 7: Monday - CS50 2011 - Harvard University
CS50
53 Week 5: Monday - CS50 2011 - Harvard University
Week 5: Monday - CS50 2011 - Harvard University
CS50
54 Week 5: Wednesday - CS50 2011 - Harvard University
Week 5: Wednesday - CS50 2011 - Harvard University
CS50
55 Week 7: Wednesday - CS50 2011 - Harvard University
Week 7: Wednesday - CS50 2011 - Harvard University
CS50
56 Week 8: Monday - CS50 2011 - Harvard University
Week 8: Monday - CS50 2011 - Harvard University
CS50
57 Week 9: Wednesday - CS50 2011 - Harvard University
Week 9: Wednesday - CS50 2011 - Harvard University
CS50
58 Week 8: Wednesday - CS50 2011 - Harvard University
Week 8: Wednesday - CS50 2011 - Harvard University
CS50
59 Week 10: Monday - CS50 2011 - Harvard University
Week 10: Monday - CS50 2011 - Harvard University
CS50
60 Week 2: Wednesday - CS50 2010 - Harvard University
Week 2: Wednesday - CS50 2010 - Harvard University
CS50

Related Reads

Chapters (26)

Introduction
1:12 Python
3:10 Compilation, Interpretation
4:32 Hello
15:09 Types
16:51 Speller
25:56 Image Recognition
31:06 CS50 library
32:22 Conditionals
35:09 Variables
36:33 Loops
41:50 Calculator
51:35 Compare
59:31 Object-Oriented Programming
1:05:20 Meow
1:14:38 Mario
1:35:45 Scores
1:40:35 Uppercase
1:43:57 Greet
1:48:27 Exit Status
1:51:02 Search
1:54:15 Phonebook
2:00:49 Compare
2:04:11 Swap
2:05:13 CSV
2:11:01 Speech
Up next
Marketing management for ugc net| Important topics of marketing management ugc net commerce dec 2023
Bhoomi Learning Centre~Dr. Muskan
Watch →