Python - Intro to Computer Science - Harvard's CS50 (2018)
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.
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.
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