Python - Intro to Computer Science - Harvard's CS50 (2018)

Python - Intro to Computer Science - Harvard's CS50 (2018)

Show Video

This. Is cs50. Then this is lecture 6, and you recall that last week we introduced, web programming, by way of HTML, and CSS or, at least the building blocks just we don't actually have the ability to program, yet it's just markup, HTML. And CSS was stylisation thereof, but we introduced this metaphor, last week of a protocol, called tcp/ip, and we related it to of course an envelope, and, on this envelope virtually, on the front was at least two pieces of information and, if anyone remembers what. Were those two pieces of information in the to field. Someone. Else who we didn't hear from recently. Yeah yeah. An IP address a numeric address that uniquely identifies your computer, and someone else's computer and one other thing if you remember, oh. Come. On who's like two, minutes ago okay yeah a, port. Number so another number shorter, number that's just the number like 80 or 443, referring. To wet HTTP. Or HTTPS, or other, numbers like 25 for email and the like and so together these unique addresses, allow, you to send information to, not only a specific computer but a specific service, running, on that computer and in, order to actually request information from, that server there's, this other protocol, called HTTP. Hypertext Transfer. Protocol this is what's, inside of the envelope so when the server opens, it up metaphorically. Looks inside this is the command that that server reads, in order, to decide what it should actually respond, with and so this request here is telling. The server otherwise, known, as dub-dub-dub, dot example.com, in this particular example to send. Back what exactly in. Its own envelope, to me and my laptop if I were to request this a. Specific. Webpage and someone else which web page specifically, presumably, yeah. So index.html, which we said last week just tends to be the default, file name on a server, for a web page that's just selected, by default and, it doesn't have to be called this but it's a human convention, and the rest of this is just a verb saying literally get me that file this is just telling the server what version, of HTTP, I speak so that humans can improve it in Mato and upgrade, it over, time but this would tell the server to return, index.html. Meanwhile, we, saw more sophisticated, get queries, when we started talking about Google and any. Website. That has not just a front-end like HTML, and CSS but also a back end and a back end is where the logic is where the server is and the the interesting, worked ultimately, and so, this slash search, indicates. Some kind of software running on Google, servers as of last week that simply responds to requests, and what did question mark Q equals cats do. Or represent, in that. Demonstration. Yeah. User input so the question mark just says that's it for the file name or the URL here, comes the users input Q, is just the literally, the HTTP. Parameter, or input, that Larry and Sergey founders of Google 20, years ago decided would, represent the users input Q for query equal, just means that query that the human typed in was cat but, the human doesn't even have to type this in once you understand HTTP. If you really wanted to be kind of a nerd you could go to WWE. Comm slash search question, mark Q equals cats and it would induce the search for you because at the end of the day that's all the browser is doing when. You have these web forms, that you now have the ability to create it's just automating the process of generating, these HTTP. Messages. Now the server hopefully, responds, with a message you never ever actually see, HTTP. 200, which literally means okay. Of course many of us have seen numbers other than. 200. Appear like what. 404. Which means. File. Not found now why the humans. Decided years ago to tell human to tell other humans what that number merit code is I mean that is an uninteresting. Detail but the world for whatever reason, has revealed in many, websites 404, but it just means the same thing everything, is not okay a file, was not found you, might see something else like this we saw this with Harvard in fact curiously, that Harvard had moved permanently now.

Harvard, Was responding, to certain queries, with HTTP. 301, x' in. Order to achieve what feature, or effect. What. Yeah. Redirection. So this is kind of a low-level way of describing it but 301, even though it says moved permanently that's, a more technical hint to the browser saying Harvard moved not to whatever URL you just came from but, to this URL specifically. And now hard was probably if you recall redirecting, me from what URL, if I wasn't already at that URL where might I have been. So. Maybe. Calm if they actually own multiple domains and we're redirecting that could work what else yeah. Yeah. Maybe I just typed in HTTP, and Harvard in the interest of security wants, to force my browser to, request. Me request. This page again via, HTTP. Sometimes, a website might prepend, the www. If you haven't typed it in or you can be redirected most, anywhere in fact if you go to see a swifty zone website by just typing cs50, that Harvard edu, watch, the URL you'll be redirected to a more specific page depending, on the time of year, so we use these tricks as well 404. Not found might look like this, but inside deeper, that metaphorical. Envelope is the actual contents, of the web page so you get back not only these HTTP, headers as they're called in the top of the, response so to speak but you also get back HTML. Yet another, language. We looked at this one actually a language but not a programming, language these, tags tell the browser exactly, what to do in to render um, we introduced this style tag though what, did that allow us to do that HTML alone did not. Yeah. Use. CSS, to beautify the site and just make it nicer HTML, for the most part is about structure. And about, tagging. The contents, of your web page in a way that the browser finds helpful but CSS, is really for the users benefit, at the end of the day and his or her eyes because, it really lets you control font size and positioning, and lower level stuff that you might have started tinkering with with, the most recent problem set now we'd proposed, that you probably shouldn't just start typing CSS. Inside, of your HTML, page because it's just a little harder to maintain as your examples get more sophisticated so you might factor it out and odds are you did this for the problem set because when making a home page if you have the same CSS Styles across multiple files it would be pretty silly and inefficient. To copy and paste them again and again when you can factor them out like this lastly. We looked at JavaScript. Last time another programming, language that's super similar to C at least at first glance but it actually gets rid of a lot of the lower-level headaches, like pointers, and memory addresses in that that we've struggled with in recent weeks but most important, was how we used it so you can consider a web page like this as once. It's loaded by your browser's just being a tree structure thinking back a couple weeks to our discussion of data structures, and each of these nodes, in the tree we. Saw in JavaScript, can be manipulated. And via that very simple principle, writing, code that modifies, this existing, tree, in the computer in the browser's memory means, you can make much more dynamic things, like Gmail and Facebook and, any number of websites that are constantly, changing you did not do this yet for the problem set you made static, web, pages just by hard coding HTML and CSS but, starting next week once we have thanks to this week the vocabulary, of Python will, you start to make things more dynamic, and then even bring back into play JavaScript. Bringing all these various threads together. And. To include the JavaScript recall we used either a script tag at the top or we factored it out to a file or in some cases it's necessary, or beneficial to. Move it down to the bottom of the file or, factor, it out like that but, more on that down the, road so, many questions on last week or on HTTP. HTML, CSS. Or, tcp/ip. No. Yeah. Good. Question so in what cases would you put the script tag up at the top versus at the bottom if the, code you're, writing in JavaScript manipulates. The Dom the tree that I had on the screen just a moment ago the catch is that that tree needs to exist, when your code is executed, so if you for instance have, JavaScript, code up here in the head of your page but. The nodes in the tree the, tags that you want to manipulate and changing things to red to green to blue like we did last week or making things blink or down, here in the page you, can't write your code up here and have it changed things in the page down here because it's happening out of order so similar in spirit to see where things have to happen in the right order if you want to change something down here your code needs, to at, least be down here or you, need to use some fancier, techniques to say I'm, gonna write my code up here but, wait a few seconds, before executing, it until the whole bud page is loaded.

So, For the most of the examples we looked at this was not an issue but we'll come back to this. Before long all. Right so let's, now take, the same approach that we did last time of introducing. One language by way of another you'll recall of course that we started the whole semester with scratch and then we transitioned, a few weeks back now to see last week we made some comparisons, with JavaScript, let's do the same thing briefly, with Python but then spend more time at the keyboard comparing, the two to see what actually is different. About these so why in another language though first we have scratch. C. JavaScript. Python. Not to mention HTML, and CSS for, different purposes like why do we have all of these darn languages, already why, didn't the humans just decide that's it we're all using scratch, we're all using C or JavaScript, or Python, what's. Perhaps the intuition, behind that. Why. Are there so many damn languages, not, to mention in this one course yeah. Say. Once more. Yeah. Different ones are good for different things and this probably goes without saying for something like scratch right it's so visual it's so graphical, and animated, like it makes sense that the puzzle, pieces are that the language itself is based on puzzle pieces and dragging, and dropping so maybe languages, are tailored to certain, applications, but is that let is, that true for C Python in JavaScript, which are all text-based languages we'll see. Ok. Different levels of abstraction. Good. Okay, good, bringing back to abstraction, does make sense see is indeed like very low-level literally, having the ability to manipulate memory. And via pointers, and so forth and that's great because you can do anything you want with the computer but it comes at great risk and great cost one the cost is human time like it's just painful to write that kind of code sometimes to. It, also. It's. Also very risky because if you make a mistake even a simple mistake the whole computer can crash and we didn't see examples of this but you can make the your code vulnerable, to a hacker if he or she is able to somehow exploit, a memory related bug and read all of the passwords in your program or something like that so with great power comes great responsibility it's, kind of the mantra of C down here but JavaScript, we saw allows, us to do things a little more high-level like, there were no pointers, there was no memory we didn't talk about things at that level we talked about things at the level of a tree a Dom in memory and changing colors and and, positioning. Of things on the screen and that's indeed a higher level now python is not. Necessarily. Even web-centric, it's more of a multi-purpose, language, people use python to write command-line programs like we will soon at the keyboard like we've been doing with c you, can also though use it as we'll see next week to generate, other languages, so next week we will write code, in Python the language we're about to see to, generate, another language HTML and, CSS some of you probably noticed in your home pages, that you had some redundancy, you probably had similar tags, or similar structure may be a similar menu, across pages Python, and other languages, will let us factor that out and generate, those commonalities, a lot more easily among many other things and it's also arguably, easier, and faster to write because it comes with so many more features as we will soon see so in fact you know what let me do this let me go ahead and open up cs50. IDE, let. Me go ahead and create a new file and out. Of curiosity of our recent problem sets what was maybe among. The most challenging, programs you've written. Ok. Crack was a good one what else. Resize. Recover. Yeah definitely the forensics, ones and more people probably did recover and resize so let's take resize, for example, so let me go ahead and write, a program in a file called resize PI for python instead of dot c and see, if we can't spend what few, hours couple, days as, you probably didn't see, resize, well let me go ahead and do this I'm, gonna go ahead and. Let's.

See First I'm gonna import some features that just come with, Python, and I'm gonna go ahead and say from. Sis import, Arg V and, I'm gonna go ahead and also do Maya from PIL, import, image, don't know what yet what these are will tease this apart in a moment but then let me just do a check if the length of rather. If the length of Arg, V, does. Not equal four I'm gonna go ahead and exit for the user and say the usage of this program, is, Python. Resize, da PI and, in, file out file so even though some of this should look cryptic at the moment there's some commonalities, are V you recall from C and this usage, string, that we printed out whenever anything went wrong that looks very similar in spirit to C and what, did we do in resize, if you implemented, resize, like the less comfy version to increase, the size of things you, probably declared, a variable like N and, got sis, dot or rather, our, V bracket 1 to get access to it I'm gonna go ahead and convert that or cast that to an int you probably had an in file variable, that gave you access to like argh v2 you probably had an out file variable that gave you access to our v3, and so forth and it, turns out in Python if you know what I can actually use a library, code that other people have written let, me come up with a variable called in image, like in file this is my input image, and that's, gonna equal image. Dot open because I want to open this thing called in file and then, the width let, me get the width in the height of the existing, image by doing input image size, and then, let me go ahead and make a new image out image, I'll call it which is going to equal the, input, image calling. A resize function and, doing, the width times. N which is the number the human probably typed in an H a height times, n which is the number the human, typed in then let me go ahead and just save the out file as. Follows, out file okay. Done. Problem. Set 3. Tada. Okay. Either really exciting, or really really disheartening, perhaps right so with the right language as you say can you solve problems, so much more easily, now, I'm being a little disingenuous because, I'm also, leveraging, what's called a library and we had access to these in C and undoubted, that we could have dug a little deeper on the Internet into, other. People's available, code and found maybe a library for bitmap files but. Notice. That there is no dealing, with padding, now there's no dealing with arrays there's, no dealing with memory because I'm using the right tool for the job and if I wrote this code correctly, and let me cross, my fingers that I didn't make any typos, let me go ahead here, and, get. Myself a copy of smiley, which, I brought with me so. That was the tiny little image from last week let me go ahead and open this in the IDE smiley, super. Small just a few pixels there and let, me go ahead now and run Python which we'll see why in a moment, resize let's, increase this by a factor of 10 increasing. Smiley, and call it out dot, BMP, now. Let me go ahead and open out dot BMP and voila it. Indeed seems to work right, no funky colors no like weird sizes. No padding, no padding of all things it's, just now Python, so you can probably glean some, of the logic that's going on here but some of it certainly should and probably does look magical, so, let's use today the tease this apart and, appreciate not only what you can do with another language like Python but, how it's similar and different and how it actually is built, upon something, like C so let's do some comparisons, first so that we can see that it's not a huge stretch to introduce yet another language so, quickly, so recall that in scratch if we wanted to set a variable like counter to zero you might simply do something like this setting, it equal to zero at left in C we would do the same thing here at the right in JavaScript, this instead looked a little different what did we do in JavaScript. Yeah. We used let instead, because, we don't specify explicitly the. Type but we do need to tell the computer let me have this variable called counter, in Python.

It's, Going to be that. So. We've gotten rid of the type still, we've gotten rid of any mention of lets or another, keyword and we've gotten rid of perhaps most gratifyingly. My colons are gone no, more semicolons. And no more curly, braces in the way you've seen them thus far so that was C JavaScript. And now Python so how about something like this in pipe scratch if you want to increment a counter by one you would use a block like this in C, we would do the same on the right here in code in JavaScript, did it look any different on the right. No. You, probably haven't had a case you haven't had occasion to use this yet but one of the sort of revelations, of JavaScript was that's, also JavaScript, it was identical, something. Like this, though, is Python. So, it's almost the same but I've gotten rid of the semicolon but the logic is exactly the same set, counter on the left equal to whatever it is on the right plus one additional value, what about this this in C had what effect. Incrementing. The variable so this is exactly the same it's sort of a nice shorthand, notation, for doing counter, equals counter, plus one which just gets a little tedious to type we had that same syntax in JavaScript. And you can probably guess in Python, what's it going to look like. Same. Thing minus the semicolon, all right so a pretty nice pattern so far languages, just keep getting trimmer and trimmer if you will in C recall, that we could just do plus plus which was another. Trick for automating, that same process javascript, allows for the same and if. You really like the syntax I can't, show you a slide for Python doesn't exist can no longer do plus plus so we're paying a price the, author of Python did not include this in the language but that's ok we at least have this one which is not too horrible, so what else do we look at last time an, if condition, like this comparing, if X is less than Y and C it looks like this in JavaScript. It looks like this, same thing in Python. It looks like, this. So. Gone are the curly braces, added. Is a colon, and what you don't see yet is that indentation is, going to be important. So any of you have been a little fast and loose with style 50 and like, we've seen it office hours all of your code however many lines you've written for whatever reason is all aligned on the left and nothing is actually indented, now, pythons not going to tolerate that Python requires, indentation, for, logic and so this is actually a stylistic, feature of the language it forces, you to adopt, good visual, stylistic, habits because the code just won't run if you haven't indented it properly so any thing that's gonna happen if X is less than Y needs, to be indented, say four spaces, underneath that, :, what, else have we seen in CR in scratch we had this block four ifs and else's and see it looks like this in JavaScript.

It Looks like this in Python, it's gonna look like this albeit, with indentation below, each of those colons, how about this when we had three-way, a fork in the road if else if else in C it looks like this, JavaScript. Looked the same in Python, looks, a little funky it's. Gonna look like this l if, but three colons this time too what else we also looked at forever loops in scratch in C, and in, JavaScript. You could use exactly, the same syntax, in Python. Almost. The same gone or the curly braces added, is the colon and the slight subtlety if you noticed. True. And false are now proper, nouns if you will capital T capital F is necessary, to write how about a for loop so in scratch we could very easily say repeat this 50 times C. And JavaScript is a little pedantic and that you have to initialize, an increment and check both. C and JavaScript take that same approach although in JavaScript, we of course used let instead. Of int Python. Is a little more succinct, although a little less explicit. Step by step you. Just do this for, I in, range of. 50, is the way of saying start, iterating at, zero count all the way up to but not including 50. Thereby giving you a range, of value, so this is the one that's perhaps the most weird thus. Far but still a little more succinct to write so in C we had so many datatypes bool char double, float int long string, the last of which of course came from the cs50 library and there's others that you can use in C as you might recall from. Problem set 3 perhaps in Python, we're going to short in this list at least initially to, just these data types in Python we're, gonna have bulls for true/false floats. For real numbers, intz. For integers and then stirrers for. Strings just a little more succinct but it does actually exist, stir in Python is a real thing it is not a cs50, addition. There are other data types that come with Python in fact this is where the language gets powerful, and those of you who came from a Java background or C++, those. Of the subset of you who have programmed before you, have more features in Python just like you do in those other languages, that we did not have in C, in, Python you have dictionaries. Or hash tables, you, have lists, which are arrays but that can automatically. Resize, you don't have to decide in advance how big or small they are range.

We Just saw it's a range of values like 50 of them set, in the mathematical, sense it's a collection of things that, ensures you don't have duplicates in that collection, and then, tupple, is a combination, of things kind of like for math when you have X comma Y or latitude comma longitude, anytime, you have pairs or triples or more of things those, are called tuples, and those are common in math, courses and higher-level CS theory classes as well but, we do give you at least in this first week of our look at Python a few functions from cs50, among, them get float get int and get string, which behave exactly like, their SI counterparts, and this is just going to allow us to start, writing code very reminiscent of what we did the last few weeks but, let's, consider what's going to change as we're about to start writing our own programs, in C. When you want you to use the cs50 library you of course included, its header file that, syntax, is going to change in Python so that for this first week when you want to use the cs50 library you're. Going to instead say from, cs50. Import. And then, a comma separated list of the functions, that you want to import or use in your code so it's a little more precise this syntax it's not saying give me everything, give, me this this and this other thing and if you want to use one or more you, can just separate them by commas as an aside especially those of you have seen Python before there's other ways to do this many there's, several approaches. This is perhaps the most comparable, for our purposes today what. Else you're gonna have to know in C, you, had to compile, your code and, you did so with clang like this and then you ran your program with dot slash hello or more, simply you did make hello and then we figure out the command for you in the IDE or the sandbox or lab in Python. You're, gonna skip the compilation step when, you want to run a program in Python you're gonna do just what I did quickly before you're, just going to run the command Python, and then the name of the file that you want to run and the reason for this is as follows in, the world of C recall. That we had this sort, of pipeline process, where we have our source, code as our, input and then. We wanted to get to the point of machine code the, zeros and ones and. What. Was standing in between source, code and machine code just, to be clear what. Process. Yeah. So compiling so we had a compiler, in the middle whose purpose in life is by definition to. Translate, one language to another it happens to be an English like language to a computer, like language but a compiler is a general term that just converts, one thing to another and so this pipeline for C looked. Like this and that's why you had to run clang explicitly, or make you had to induce that middleman, operation, to convert the language to something the computer understands, Python.

And Other, languages. Are not typically, compiled, in the same way they're generally said to be interpreted. Whereby. You, don't compile them into zeros and ones and then run the program you, instead, run, a program, that someone else wrote called, Python and, that. Program is by definition a interpreter, and that interpreters, purpose and life as the word implies is to read your code top to bottom left to right and just, do exactly what you tell it to do step by step, by step without doing the upfront. Work of converting. Things to zeros and ones so in the human world if I speak, English and someone there speaks Spanish and we, don't speak each other's language, we might put a third human in between us obviously a human interpreter, the role is very similar, the interpreter, listens to me and then translates, that to something the computer understands but it doesn't get into zeros and ones it just goes from one directly to the other so the difference here in Python is that you still are going to write source code like I quickly did for resize and, ultimately. We want to actually get it into a program, called an interpreter and. So. The step ideally, just looks, like this but, as an aside python, is a pretty sophisticated language. And even though we have the pleasure of running it just with one step instead of these two steps there actually is as an aside some, magic, going on underneath. The hood and for the curious there actually is for, performance, reasons a compiler. Built into Python that, actually converts it to something intermediary. Called, byte code and byte. Code is what's actually interpreted. And so this is why Python while, potentially slower, than. C at certain tasks because you're not going to the low-level zeros and ones can, actually be used in business applications, and popular websites and such and, really work very well and so, it, can be highly performing, as well but more on that in a little bit so with that said if this these are the differences not only syntactically. But also mechanically. Let's go ahead and actually write, a program so, let me go ahead and go into the IDE let me close our examples, from before and let's start more simply because resize was a mouthful all at once let me go ahead and create a file called hello, dot pi and instead. Of writing this program in C let, me go ahead and just write hello world so, let's go ahead and do this print. Hello. World done, that's. My first program in Python and truly my first program in Python not sort of coming out swinging with resize, so, what is not, present. In this file that was in something like hello dot C. There's. No main function, necessary. Here what else is missing. There's. No mention of printf it's instead print which is a little more human-friendly. There's. No mention of header files or libraries, at the top of the file just, I just dived right in and got to it yeah. No. Semicolons. What else. What. Else yeah. No, backslash-n I probably haven't run it yet but I think I will get that for free this time with Python I don't have to be so explicit was there another hand here. There's. No F in printf yep, something. Else there's. No yeah. There's. No indentation, though. To be fair there's only one line but there's no indentation that's fair that's fair there's no curly braces as well there's no mention of intz there's no mention of void I mean my god like why, didn't we just do this last time and so this is why languages.

Evolved People realized years ago like GC is serving as well the fonts how you understand, pointers and the syntax okay I got it but my god it's just so tedious to write even the simplest of programs because, I have to do hash, include, standard, IOH int, main void I mean all of this syntactic. Overhead, that's getting in the way of you just doing the work you care about which in simplest form here is just printing, HelloWorld so, Python and a lot of more modern languages, among them Ruby and PHP and. Others just get rid of a lot of that overhead so that you can just get down to work more quickly right, away so how do I go ahead and run this and see recall. I would have done like dot slash hello dot pi but we just said a moment ago that's not the right approach how, do I go and run this program. Yeah. So I run literally a program. That is coincidentally, called Python itself, that, is the interpreter, that's the man in the middle between me and my spanish-speaking, friends that, just has to convert, hello, dot pi into, whatever the. Computer itself understands. And so there indeed we have hello world and as you notice there's no backslash, n on my code but I am moving the cursor to the new line so, Python just decided you know what it's so damn common to have new lines let's just add those by default no the price we're gonna pay is it's a little annoying to get rid of them but we'll see that in a little bit too so just a trade off all right let's do another one that's just a simplest, of possible, programs let's, go ahead and do say something a little fancier, that. Allows us to do something. More, than that so, let's go ahead say, and compare. Not just that but, let's actually go get some user input so, for user input there's, a few ways to do this we'll do it the cs50 way initially but these are training wheels this week that we'll use for just a week before we take them off just bridging us from C, to PI. Let me go ahead and call this string 0 PI because I'm dealing with strings and let me go ahead and do s. To, give me a variable getstring, let me prompt the human for his or her name like this and then let me go ahead and say hello, so-and-so, and, now I just have to consider how to print out their name and in Python I can, actually just do this I don't need to do % s I don't need to put, a second, or I do need put a second comma here but, I can just do this which is a little simpler, and this is not correct I'm not, practicing what I preached.

Get. Rid of the F just print what you want to print indeed so, s notice, is apparently, a variable, because I'm assigning it a value from right to left but, notice. That I'm not specifying, the type so python does have type stur we said is the string equivalent, but you don't have to mention it Python like JavaScript will just figure it out even without a keyword like let but I do need to add one thing. What's. That. Yeah. Getstring, is the cs50, thing and we're only going to use it for a week but, I do need to import it in the syntax with which to do this is to say from the cs50 library import. A function called getstring I don't need to import anymore with commas that one suffice is for this program yeah. Like. Not. Indicating. Ah, sure. Let me come back to this in one second let's run this program first two premise, trait that indeed does what, we saw do last week and let me go ahead here, and do. This, time, Python. Of. String. Zero let. Me go ahead and it's just waiting for my name so I'll type in David hello, David but as you propose what, if you wanted to flip this around well. Suppose, I wanted to say the person's name and then. Something. Like. Hello. Because, I'm just excited to see them instead let's, see what this does let me go ahead now and run Python of string zero type. In my name and it's. Almost what. I think you intended, but there is a bug an aesthetic. Bug at least so it seems with pythons print function, you don't need to use the placeholder, like percent s but. It would seem to presumptuously. Add a space. For you after. Everything, you're passing, in as an input to, print. Itself so notice print is taking how many arguments according, to this highlighted, portion. How. Many arguments might you infer. S. -. Yeah so - one, is s comma, and then the rest is what's highlighted in green here yes there's a second comma there but it's inside of the string so just I can see that's sort of a red. Herring there's, only two arguments, here but it seems that the print function and you would know this by reading that documentation, if you pass in two or three or more arguments it prints all of them but separates, them with a single space so this isn't quite right so this is actually great motivation, for cleaning this up if I want to actually improve this program and tidy, it up a little bit let me do that in version, one here let me create another file called say. String, one dot pi let, me start where we started a moment ago and let me actually use a placeholder akin, to C so if I want to do for instance hello, so and so it turns, out you can actually say, hey, Python, put, a variable, called, s right, here, however. If I. Run this as is, they're still gonna be a bug it's not quite solved, yet when I hit enter now and type in my name alright. This is obviously stupid-looking, so. It seems that I need to tell Python, that, this string that I'm passing in hello comma so and so is a formatted. It's a placeholder stream, that it should make some changes, to and this is a little weird cryptic, syntactically. In Python but the way you do this in Python is, you. Put an F before the string itself so. I'm sorry we should we got rid of the F a moment ago so you just called it at prints then we're reusing a different F here, and it's stupid-looking syntax, admittedly but this just means hey python the following, double quotes or single quotes that you're about to see should, be formatted, by you in a special way and it literally goes at the beginning of the string even though that does admittedly, look weird but if I now rerun this Python string one and type in my name now now, it does the substitution, so I can flip it around logically. Much more flexibly, now and do, something like Hello because. Now I'm passing in one argument that print will format for me so when I type in my name now I'm not going to get that superfluous. Space, and now I have complete control over the, formatting of the string so you know sorry one two steps forward one step back perhaps, and tactically, but it does allow us to do what we want us to do we could write the same program using int and floats using get int and get float would look exactly the same you don't need to worry about percent s versus percent I versus, percent F you just type in the variable name inside. Of those curly braces. Alright. Let me go ahead and do. Some quick, math let, me go ahead and do this let me go ahead and create a new file we'll call this in spy, for integers and let, me go ahead and get this, access, to, how. About the, cs50 library's, get, int method, or function which exists, then let me go ahead and declare a variable called X and get an int from the user and just prompt him or her for X then, let me go ahead and do the same thing and just get Y, from them as well and then, down here let me just do some simple math and we did this way back in week.

One By, printing as follows, let me go ahead and just print out X plus. Y equals. And this is what's cool now about this curly. Brace feature, you, can actually do. Not. Just variables. Names but you can do simple, operations, in there too I can literally do math inside, of those curly braces, and print, out that value, but of course this alone is just gonna literally print the curly braces what do I have to add yeah. So it looks a little weird but, this now will solve that problem, it will print literally, X plus y, schools whatever, the actual sum is. Format. Format, the following string for me good question let's do just a few copy-paste. But change the operator, here, so, f X, minus, y I want to see what this looks like X. Say, what do we do last time multiplying. By, Y I want to do that math to I can divide as well, and. Then we had one more which was modulo. Or modular, arithmetic which, recall was the % so syntactically, it's identical, to see we're just adding this curly brace notation just for the print function right now let, me go ahead and run this python of in stop hi and let. Me go ahead and do one and say. 2, so. 1 plus 2 is 3 1. Minus 2 is negative 1 1 times 2 is 2 1. Divided, by 2, is 0.5, and 1 then divide by 2 and take the remainder is 1. So, I think this checks out mathematically. But. You should be a little surprised, by one of these outcomes. Segan. Yeah. I'm getting a float like Python. Itself seems to affixed a bug. In C itself, what, happened in C when you divided one in integer by 2 an, integer in C. You. Would get another integer and what's the closest integer you can represent that doesn't have a decimal point. 0. Because C, would truncate, everything, after the decimal point, and yet Python seems, to a fix this problem and this is actually somewhat recent phenomenon, and this is a huge religious, debate as to whether or not you should just keep the historical, definition, of division. Which, is floor division so to speak or we should make it truly division, like we all grew up learning in school Python, took the latter approach and made division, mean division, through division where if you divide 2 inch you get back a float of course, this is a problem if people want to write code that assumes that it's going to be truncated, that can actually be a powerful, feature so.

It Turns out and you won't have terribly, many occasions, to use this but, the compromise in the world was alright if you really want the old behavior of the division. In Python, we. Will give it back to you you have to use two slashes so, again another one these two steps forward one step back but it's there so, can still be solved in the same way and this if I save it and rerun, that same code one and two and now I get back zero just as I would in C which does have some applicability. Let's, do one other example now involving some numbers and let me go ahead and call this floats. Dot pi and, let me do the same thing from, cs50, import get float this time so I can deal with floating point values let me declare a variable X and get a float and we'll ask the user for a variable X then, let's go ahead and get another float, and just as before call it Y but, this time both of them are indeed floats then let me go ahead and do some math X plus y equals, Z to, give myself a third variable and then let me just go ahead and print out a similar message X, divided. By y, equals. Z. All. Right and let me go ahead and save this clear. My terminal and do Python afloat stop by. 1/10. This time and I, get damn it bug how do I fix this all. Right so just simple F make it a format string no big deal so let's rerun this one 10, okay. Whoo-hoo. That's. A new one. What. Is going on there. I did. Define Z in the line above it what was your comment I, did. Use X plus y but I think I know I, know okay I'm sorry let's um you. Okay so if we can fix that let's uh, sorry. There. Okay. So, 110. Mmm. Still wrong. Good. Catch thank you though. Why. Is 1 plus, 2, 11. Or 1 plus 10 11. Yeah. Oh. Wait. Wait wait sorry. Brings. Me back to my earlier point us as to how tired I am so. This is correct so Python does Matt sure. Correctly. What. Okay. Horrifying, all right so now let's. Do division and try to make the point I think I meant to make late last night where, if I do. 1/10. Ok, 1/10. As expected. Does. Actually work here, so 0.1 that's correct but remember in C let me dig myself out of this all remember and see what. Happened, if we dug a little deeper and we looked a little past the first decimal point so how do I do this in Python it's actually pretty similar let, me go ahead and not just show myself Z, but, go ahead and print out two let's, say two decimal. Places that same value the syntax here is weird it's different from C but, you literally take the variable that you want to format you, put a colon and then a dot because you want to adjust the dot and then you want to say something like 2 F so, this is saying hey Python, format. The, variable, that's to the left of the colon using. A two decimal, points and by the way it's a floating point value so this F has a different meaning this is F isn't float the, F to the left is in format, so, let me go ahead and run this. 1/10. And okay, still looking pretty good let's do maybe three decimal. Places save, that rerun, it. 1/10. Still, pretty good let's get a little ambitious. Let's do it 50 decimal places out. 1/10. And damn it Python, has not fixed this fundamental, problem so, we describe this problem as. What's. The sort of buzzword here to sort of explain, or. Forgive this issue. This. Is an integer overflow, related in spirit integer overflow literally, happens when you're doing lots of addition, and something's rolling over from a big value to a small or even a negative. Similar. In spirit yeah.

Yeah. If you want to have an infinite, amount of precision, all the way out you need an infinite amount of memory and no Mac or piece of your phone has an infinite, amount of memory at some point a line is drawn in the sand and you can only be so precise, and so imprecision. Was the analog, in, the floating-point world to overflow, recall where if you only have a finite number of bits you, can do really well up to a point but eventually the computer's got to estimate, that value, for it to you because you can't represent an infinite number of values so, this is to say Python is just, as limited, fundamentally. As some other languages, like C so we've not gotten rid of all those problems but frankly, in the world of data science, and analytics, it's certainly important to have precise, mathematics, so there are solutions to this problem, but it requires special libraries, typically, use importing, something that, allows you to use as much memory as you want more, than just the default amount, of memory so, that problem, there still exists, let me go ahead and open up one other example here and. In fact in C, you'll, recall that we had this example here, in C we had a program, called, overflow. Dot C and, notice. That this code in C from, a few weeks back just, multiplied, I bye, - bye, - bye, - so it was doing exponentiation, so to speak 1 - 2 - 4 - 8 16 32 64. And so forth what happened if we waited, long enough and watched this program a few, weeks back. Yeah. We hit like roughly five billion. Or. Four billion or rather, we technically hit I think 2 billion and then it rolled over and it actually created a problem so let me actually do this let me go ahead and make overflow, so, we can demonstrate the points that you made earlier about integer, overflow which is indeed this one let me go ahead now and run overflow. I'll expand my window just so we can fit a little more in the screen and as. This runs. Whoops let me fix this here. We go, let, me go ahead and make overflow and now, one two four eight sixteen. Thirty-two and, so forth it's a little slow to start but doubling and doubling is going to get us up to a big value pretty quickly this is indeed gonna overflow once we hit roughly 2 billion why why, 2 billion, give or take. By. That value in C yeah. Yeah. That's how much an integer can store because we're calling C an INT is typically 32, bits or 4 bytes and with 32 bits you can represent 4 billion possible, values, and if half of those values are positive and half of them are negative it stands to reason that the highest you can count is roughly, 2.

Billion And indeed once we try to count up just doubling 1 billion we, overflow, so is your point at to your point earlier overflow, is still an issue but in the context of integers. But now let's try a python version of, this let me go ahead now and open up, overflow. Pi which is a program I wrote in advance it's on the courses website as always if you want to take a look more closely and, if, I go into this file in weeks, one, overflow. Dot pi we, see this code so it's almost the same but notice I'm using another library, that we've not seen before from, time imports, leap it's kind of cute so this allows me to sleep for a second that's going to get tedious quickly but that's ok let's do this real fast if I go into the source 6 directory, weeks. 1 and run python of overflowed pi it's, the same function, or same program, functionally, but. Honestly this is getting a little tedious let's go ahead and not, sleep, for a second, every time save. And reload let's just run the thing whoa. Look. At it go only. Up there look up there. What's. It doing differently. It's. Counting, a lot higher than 2 billions so what might you infer about integers in Python. Say. Again. Okay. The integer is defined to be quite the number of bits and indeed that's the case the reason Python is not actually this slow it's because we're running a web-based IDE and the Internet itself is a little slow and so what's happening here is just the internet is getting in the way but suffice it to say that python is counting up way way, higher, than c, was and that's the power you get by just using larger, datatypes we could have done this in c we could have used longs for instance but notice that with python you just give more by default out of the box let's, go ahead and take a five-minute, break here and when we resume we'll introduce some more syntax and solve some more problems all, right so let's take a look at a few other examples that, are comparable to what we did back in week 1 and look at a few from week 2 and 3 and really, take a look not just that the syntax ultimately but some of the features of Python, and of course we need the ability to express ourselves conditionally. Or logically, with control flow and so let me propose a quick program, here that we'll just call conditions, pi reminiscent. Of conditions dot c some time ago let me go ahead an import from cs50. Get. Into this time and get myself another X with. Get int X from the user then, let me go ahead and ask them for get, into, Y from, the user and then let me go ahead and just compare them and so per our comparison, would scratch a bit ago I can simply say if X is less than Y then, go ahead and print out for instance print, X. Is less, than Y, just as we did weeks ago L if, X is greater than Y we can go ahead and print out X is, greater, than. Y and then we can still have a third condition else just I can see where, we print out for instance the logical conclusion X is equal, to Y so just to point out some of the differences indentation. Is ever so important, now and it's got to be consistent you can't have 4 spaces in 3 you've got to have for instance 4 all the way notice, that I've got the colons consistently, there but notice that I don't need the parentheses either, anymore Python. And. With Python there's sort of a buzzword, pythonic, there is a pythonic, way of doing things you can have parentheses, around X less, than Y or X greater than Y just like in C but, it doesn't add anything logically, arguably, and if it doesn't make your code more readable don't, clutter your code with additional characters, and so that's a general rule of thumb now python, is much more trim, when it comes to syntax, only, introducing, it when it really solves a problem which in this case it doesn't really yeah. The. Lion suits em - those are grouped right together one to the next one to the next one to the next, if, you were to put like an in traditional line between that would that break the code no, not at all I can have as much white space vertically. As I want if I want to add some comments indeed I can do that and why don't we do that in fact because the commenting syntax for Python is a little different in C we were in the habit of doing slash slash Python, it's actually a little more succinct you can just use a single hash and you can say get, X from user here, I can say get Y from user here, and then I can say something like compare, X and y and if I really wanted to I could put comments in here that is perfectly fine but I'll just keep it more compact with this particular example.

So Any questions, on the conditional, syntax or what, we've just done here. All. Right let me whip up another example this, time doing some, comparisons. This time let me create a file called answer, dot, pi which is reminiscent of a quick example we did weeks ago called answer dot C let, me go ahead and from cs50, import get. String and this. Time let me go ahead and use declare variable C and let me go ahead and get a string from the user whoops, get a string from the user for. Their answer to whatever question, it is we care about and then if it's meant to be like a yes/no answer let's check for that if C, equals. Equals y or, C. Equals, equals little Y then, go ahead and say just. For the sake of demonstration yes. Because the human presumably, meant that L if, C equals, equals n capital. N or C, equals equals little n then go ahead and print out for, instance no so, short program, but. What's are, some of the takeaways well what's different clearly, among, these lines 5 through 8 versus C weeks ago. Yeah. Yeah. Another stupid vertical bar so the ampersand, ampersand, if you want to do something or or and it together just say and and or much like scratch actually, some weeks ago notice, to how are we comparing strings. Turns. Out Python. Does not have chars per se see, did have charge single, characters Python only has strings and has strings in floats and then some fancier things but it doesn't have charge so, that's why I'm deliberately using string, but. When, we use strings, and see how did we compare two strings. Stir. Comp right because of the whole annoying, pointer, comparison, thing well it turns out now in Python if you want to compare two strings character. By character by, character equal. Equals is back and it does exactly what you expect it to do even. If it's, a full word so if you're actually checking, for for, instance yes or yes. From the human you, can still use equal equals as well even though it's more than now one character, so that's a wonderful feature too and it just makes the code more readable and a lot easier to write right. Out of the gate all right so now recall, that in PI and C we, spent a little while as well as in scratch taking a look at a few examples about, coughing, of all things and in fact in Python and C and, rather in scratching, in C we did a zero example, that looked a little like this if you want to simulate the notion of scratch the cat coughing you, might of course do this and then, if he's gonna call three times you might do this and we ran this and it just did coff coff coff on the screen and won't bother running it because it will just do that but, this was bad design we claimed weeks ago what, was the gist of why this is bad design I. Mean. I literally copied and pasted it and odds are if you're ever doing that in cs50, or in programming, more generally you're probably being a little lazy and there's a better way to do it and it's more maintainable way to do it so of course we introduced, weeks ago both. In scratch and in C the ability to in. Coughed won this, time do, a loop and I can do a loop slightly differently in Python in and C but for I in, the range of three go, ahead and print out Koff so, the syntax for the for loop is a little different but it's pretty straightforward nonetheless once you remember that you use for variable. Name then, the preposition, in and then the word range with, a parenthesis and it's the, parenthesis and the value want to care about but, then we saw an opportunity recall. To. Actually abstract. Coughing, away right a coughing, at least in our textual form it's just an act of printing something so we introduced, in version two, some time ago the, following, approach in coughed, two I instead. Defined, a function called cough that did the coughing for mean we've not seen this yet in Python so how do you define a function in Python called cough, put another way how do you make your own custom, puzzle, piece just as we did in scratch, well you define it with death and then you have it do exactly, what you want it to do by just indenting, the lines of code that belonged to that function so there's no return value there's, no need for an input at the moment but we do have the colon and we have the indentation, no curly braces nothing, else how, do I now use this function, well here's where we have a few options, stylistically. In the program the simplest, way to call this function would. Be quite simply like this go, ahead and for. I in, range 3. Go, ahead now and COFF and this, should look a little weird it looks indeed, a little sloppy but let's see if it works so if I go ahead and run Python of coughed, to dot. Pi it seems to coff coff coff but. I say this is a little weird, because. What, am. I doing, that's very different now from see. There's. No what there's. No main function. I just have some code right here on the left of the screen and yet I do have a function here and in Python this is okay because you're using an interpreter and reading the file top to bottom left to right you don't strictly need a function, called main it's just gonna interpret, all of your code and when it scenes the definition, of a function okay, it's gonna say okay got it I now know what the verb COFF means I will do this anytime I see it down here but, we're gonna run into a problem and if, indeed I did what my first instinct, was was, which was to put my the logic, the main part of my program at the top and to define coughed down here, let's see what happens let me zoom out let, me go ahead and rerun cough to dot pi and now, we start, to see the first of our error messages, and they're gonna look just as cryptic at first glance as as a clang.

And Make work rest, assured that help 50 can help with Python error messages, as well. Let's just try to parse what I do understand, coughed up High Line. 2 and module whatever, that is a name, error name COFF is not defined so what's. Your gut here what is that really what's, the explanation, for that error because coffees clearly, defined literally, with the define, def, verb, right. There on line for now. What. Yeah. I'm trying to call it before it's defined Python, is, trying to take me very literally, and it's gonna do top to bottom left to right and if it doesn't see until the bottom something it's supposed to be doing at the top it's just not going to work so there is a solution to this and it starts to get a little ugly but it's a more generalized, solution it turns out that even though main is not required, in a Python program, many, programmers, just create, one nonetheless to address this particular problem, and they specifically, do something like this def, main and then, below, it they indent everything, there and then, you need one. Specific. Feature to. Solve this problem now I've now defined main and I've, defined coffee which, theoretically, solves, this problem just, as it did in C I don't there is no notion of a prototype in Python that is not the solution to copy/paste the, name of the function up above but when I do this now, literally. Nothing happens but I did get rid of the error so. Just. Reason, through this perhaps especially if you've never programmed Python, before why, might nothing now be happening. Not. Calling, main yeah so whereas in C and frankly, in Java and a few out C++, and a few other languages main is special, it just gets called by default in Python. Main is not special I've chosen this name main just because so many other languages use it but it has no special significance if you want to call main you, have to do it yourself and so this is a little weird admittedly, but, you can literally do this down here, because, your code will be executed top to bottom left to right by, the timeline, 10 is reached both main has been defined and COFF has been defined which means you're good to go so, if I now go down here and run Python of coughed 2 now. It actually works now as an aside this, is not a pythonic. If you will most people would actually do this if the, name equals. Equals main. Then, do, this this, is for lower-level reasons, that let me wave my hand at for today but long story short the addition of this cryptic looking line solves, other problems, that we're just not going to trip over this weekend probably next so this is the common way to do it but if you just ignore that the, effect of this cryptic looking code is just to call main yourself at the very bottom of your file so when we start writing more interesting programs this is just going to become conventional, if you want to start writing functions and so forth, odds are you'll benefit, by writing a main function and putting more code in there so let's do one final example with. Coffee that, actually now, parameterize. Is the code just as we did weeks ago in scratch and see this will be coffee three pi let. Me start as I did just a little bit ago but, suppose I want to achieve this effect I want, the computer to COFF three. Times by, passing in an input I now do need, to modify COFF to take an input and in C I would have said something like int n but, you don't have to specify data, types in Python you, just have to specify the, parameter, name or the argument name so that's nice and simple and now down in here, in coffee is where I should probably say for I in the, range of, three. Do. This but, this isn't quite right what's fixed do I want to make here yeah. Now I can just pass an n so range is just a function that takes an argument that I've been hard coding is three just because but. You can generalize it within as well so, now again per our discussion of abstraction, weeks and weeks ago do we have a sort of beautiful. Version of coughing, even though it's looking way more cryptic, but by step by step by step did we get to the point of having a main function that, takes an abstraction cough do it this many times now, the implementation details, are hidden in this custom puzzle piece if you will and the whole lot of the two lines at the bottom just kick off the, whole execution of the program but that's the only stuff that's really, Python. Specific, now, yeah. Could. Use wit line. The, COFF function on line 11 yes you could absolutely just.

Do This for instance and get, rid of main again it's. Just a convention once, you start writing more specificity, cated programs with functions that you should probably introduce main just to keep it tidy. You. Come you could, do that then you're starting to be non pythonic. Like yes you could do, Koff 3 but. People, would look. Askew, at you because it's just not done that way, that's, what pythonic means yeah. Other questions. Not, in this case so the order now is okay. Because. First. Python is seeing here's the definition of main okay I got it and then it's saying here's the definition of Koff okay I got it but it's not actually calling those functions, yet the Python errors are thrown only at what's called run time the running of the program's time which, means only when main is called does, Python actually execute. Line four and then, see ooh I need to call a function called COFF but that's okay because it saw it earlier when it first read the file top to bottom so. It matters when the functions are called not, where they appear, per se in the file the. Order in which they're called other questions. All. Right. Yes. How. Did I define n is an integer this is what's nice about Python, if you want a variable or a parameter just start using it without, mentioning, its data type so the fact that I put in in parentheses. In this function means hey Python let, this function take an input called, n and it can actually be any data type in float, string, or even something else it's up to me to use it responsibly as. A number, and to call it responsibly, with, a number. Good. Question yeah. Is. Indeed. Possible for a variable to change type a good observation. So yes, python is not a strongly. Typed language so. To speak C is strongly typed in that if you make something and in it is staying an int forever, Python, is loosely, typed whereby, X can be an int initially, but if you really want to turn it into a string you can but. The the, convention there would be yes you can do that but, don't do that so python has the frankly, the sort of arrogance, of being sort of an adult language like yes you could do that but just don't like why do we have to protect you from yourselves, and so in that sense you need to be a little more responsible, about it but again there are arguments both ways that, reduces, potential, bugs that C would catch for you and this is where humans start to disagree, about the upsides, and downsides of languages, whether a language should be strongly, or loosely or not even typed at all good.

Observation, So let's look at a paradigm that was super common in see when we wanted to do something again and again to see how it actually is a little differently done in Python now let me go ahead and declare pot uh create, a file called positive, PI and go, ahead and write a program. A little quickly here so from cs50, let, me go ahead and import, get int so we can get integers from the user let me go ahead and define a main function, that simply does I which. Will be my variable gets, a positive, int, and asks. The user just, as we did weeks ago if you recall for a positive. Integer and then, just goes ahead and very boringly prints, it out so, that's all this program does and let me go ahead and just from recollection though. It's totally fine to copy/paste this cryptic looking string, we would just be remiss, in not showing, you how, most people do this so. If i do this this is a complete program except, for the fact that what, does not exist yet. Get. Positive int probably, does not exist just as it didn't in week one because we have to invent it ourselves get, in exists but get positive int does not and just for demonstration, sake let's try this python a positive, pi notice, we have name error get, positive int not defined okay so we can fix that we can literally define, or def it so get positive, int, it's. Gonna take a prompt, from the user just as it did weeks ago the string that you want to show to him or her and now, let me go ahead and get. A positive integer what type. Of programming, construct, did we use in c to do something again and again and again a. Loop. For sure but more specifically, to, do something at least once and then maybe again and again and again if they don't cooperate. Do-w

2019-02-03 13:06

Show Video

Comments:

This is the seventh video in the course. Check out the full playlist: https://www.youtube.com/playlist?list=PLWKjhJtqVAbmGw5fN5BQlwuug-8bDmabi Here is a forum to discuss CS50 with other people from freeCodeCamp: https://www.freecodecamp.org/forum/c/harvard-cs50

Is CS50 library comes by default during python installation?

Nice

Thanks a lot sir for posting free videos so that we can learn without disturbance. ❤️

Nice video banatay ho

How can I get continue to this series..?

Thank you

I need this kind of coffee. He speaks like a machine. Love it

Why do he use get_string instead of just input

because if you just use input, you've to convert it into integer using int() every time you need to input a number because by default input takes string argument. So instead he use get_int or get_string from cs50 library, they wrote this library to help beginners understand programming .

Why are you reposting CS50 videos? Is this even legal?

TECHTORMA I understand that they got permission to which is good. But reposting someone else's vidoe is without permission is illegal, I'm sure you already knew that

CS50s courses are some of the best introductory CompSci tutorials on the web reposting them actually gets them the audience that they deserve.

They gave us permission!

the best teacher in yutube I guess. I don't know why this video has less view. thank you also for helping me to improve my English .

Awesome lecture . Very lively

why this video has less views

Other news