CS50 for Business - Lecture 3 - Practicing Programming
Key Takeaways
This video lecture covers the fundamentals of Python programming, including functions, conditionals, loops, data types, libraries, and real-world applications, with a focus on practicing programming concepts using Python.
Full Transcript
[Music] Hello world. My name is David Men and today we'll be practicing programming. Now, we're not going to aspire in just a few hours together to turn you into programmers. Indeed, that's something that can take quite some time, but we will familiarize you with some of the underlying principles of and skills related to programming itself so that you're more conversant in what programmers do. You can ask more informed questions and frankly you'll have a better understanding of how software around us ultimately works. Now, ultimately, this might very well wet your appetite to learn all the more about programming and indeed you'll get some of the fundamentals today. So, a foundation on which you can build. Now, I say we'll be practicing programming because we kind of sort of did a bit of this already in the course's first lecture. Recall that I acted out this algorithm of finding someone like John Harvard in the phone book and then we translated what I did sort of intuitively that third and final algorithm to this so-called pseudo code which were tur instructions that really captured step by step the algorithm that I was purporting to implement. But we did this because there were a few salient ideas within this pseudo code alone. And to be clear, pseudo code is not some formal language. It's just my own inclination to use short English phrases to state what I was doing. You might have used slightly different words. You might have used a language other than English. But pseudo code is a nice way of just expressing your thoughts akin to au how a computer might expect step by step. Allah algorithms more generally. And recall that we highlighted a few of the key phrases here. So pick up, open to, look at, call, open to, open to, and quit were all actions, calls to action, verbs, if you will. And we called those the other day functions. And today we're going to see all the more functions in actual code as well. We then took a look at if, else if, else, and else, which were representative of conditional, forks in the road via which you can decide to go this way or this way or this other way metaphorically inside of a computer. But how do you decide which direction to go? Well, those were the boolean expressions named after mathematician bull whereby the answer to a boolean expression must be true or false or if you prefer yes or no. So person is on page, person is earlier in book, person is later in book were all questions that I might have asked myself in order to determine should I be searching to the left or to the right or maybe right there in front of me already. Lastly, we saw this phrase, go back to, go back to, which was representative of what we're again going to call a loop. Some kind of cyclical structure that makes me do something again and again and again. Probably not forever, but until some condition is true, like one of those boolean expressions a moment ago. So, these functions and conditionals and boolean expressions and loops and more are going to underly most all of today's programs. And indeed in what's called procedural programming, you see these kinds of ideas everywhere. Whether it's in pseudo code like this or as we'll see today where we'll spend much of our time, a language, a popular language called Python. Now, of course, pseudo code is not one standard, but when it comes to actually programming computers themselves, we do tend to need to standardize how we're expressing ourselves. Now, this is already beginning to evolve with AI and natural language processing where increasingly you can in fact just use your English words, not unlike pseudo code to command a computer to do something. But somehow or other the computer is then translating what you have said into the underlying building blocks that we will spend our time on today. So these ideas, these fundamentals aren't going anywhere. And indeed among the values of learning how to program is that you do learn to think, I dare say more methodically. you can break down problems into smaller problems and ultimately be a better problem solver. And if and when those processes get boring to you, easy for you. I mean, that's a good time at which to outsource it, so to speak, to the uh the AIs of the world and let them do those tasks for you. But for now, we're going to focus on exactly these fundamentals and really talk about code, the instructions that humans write in order to instruct a computer to do something step by step. So it's a translation into text, typically an algorithm which could be expressed as we've already seen in other ways like pseudo code. Unfortunately, computers, as you might recall, only understand zeros and ones, the so-called binary system. And inside of the computer's memory or RAM, there's so many of these zeros and ones. And some of those zeros and ones might represent uh numbers, as we've seen, or letters, or maybe colors or images or videos or sound, or really anything else. But those zeros and ones ultimately need to be understood by the underlying computer, the so-called CPU, the central processing unit or brain. And in fact, not all of those zeros and ones are just data files for instance. Some of those zeros and ones might actually be instructions, so to speak. And very simple instructions typically like add two numbers together or subtract two numbers or load something from memory into the CPU or store something from the CPU into memory. That is to say, when you have a CPU inside of the computer, among the things it does is these very lowlevel instructions. And those instructions have been standardized by companies like Intel and Apple and AMD and others. So each computer has a so-called instruction set, a set of commands represented in zeros and ones that it and it alone understands. So unfortunately, this is not going to be very fun for us to write if practicing programming is going to be practicing a whole bunch of zeros and ones. I'd claim that by looking at these zeros and ones, you probably can't glean what this program does. If a computer were to read these zeros and ones top to bottom, left to right, what does it do? Of course, it prints out hello world. A very friendly greeting to the human user. Now, no normal person can actually grock what's on the screen here. It would be painstaking to go through all of these zeros and ones and look up what they mean. But computers, of course, can understand this right away. But I think it would be nicer for you and me at least if we don't have to bother writing what we're going to start calling machine code, the zeros and ones that computers ultimately understand. It's going to be a lot more pleasant and a lot more productive for you and I to write what the world calls source code. So when people say code, they generally mean source code specifically. And this means the code, the text that the humans write and then feed into the computer somehow to get it converted at the end of the day to zeros and ones. So for instance, here is one form of source code. This is a language broadly known as assembly language. If it looks a bit cryptic to you, it does and always has for decades. In fact, I had to write this in school myself, a different variant thereof. And I've forgotten most of the fun most of the specifics. But this is how people program for quite some time just beyond the days of punch cards for those of you familiar with those. Once we had a keyboard in front of us that we could store data in digitally, we were essentially storing instructions and data like this. But there are some insights we can glean like push Q seems to sound like push move Q probably move maybe moving things around in memory. Calling which is a vernacular that we'll soon see. popping, which is a phrase that we've actually seen in the context of data structures and stacks. And then perhaps some familiar words, most important of which is this phrase down here, hello, world, which is going to be exactly the phrase I claimed that those zeros and ones outputed. So even though you might not believe me, it is a lot easier to implement hello world, a program that just prints that on the screen in assembly language, certainly than it would have been to implement it by hand using zeros and ones, aka machine code. But even this decades ago humans realized yeah we can do it especially with a lot of practice but this isn't very pleasant to write in and frankly it's not very readable by others unless they too are very learned in the language. So over time humans began to abstract on top of these lower level languages on top of the machine code on top of the assembly code until we had more modern languages uh like this one here. This is a popular omnipresent still language known as C that similarly just prints out hello world and it too is a bit cryptic like I don't know what hash includes standard IO in in angled brackets and then these parentheses and curly braces like there's a lot of syntax going on here a lot of text a lot of punctuation if you will but at the end of the day this program too is going to just print to the screen hello world but with a lot less effort than it would have taken me to implement that same program in assembly language and way less effort than it would have taken for me to implement it in zeros and ones that is machine code. But there's other variants of this same program. In fact, hello world is written in can be written in most any programming language. Here for instance is a uh inspired language called C++ which came a bit later. Here is a language called Java that similarly is quite popular. But here too the key detail is that that same phrase is in there. But here too, both with C++ and Java, there's a lot of overhead syntactically. And so what's nice about the language that we're going to spend a lot of our time with today in particular, is that Python, a very popular language nowadays, not just for writing code more generally, but specifically for crunching numbers, analyzing data, cleaning up data, implementing web applications, and more. Python really tends to be simpler than a lot of programming languages. And that's one of the reasons behind its popularity. Case in point, if you wanted to implement a program in Python that prints to the screen quite simply, hello world, well, you just write this print open parenthesis quote unquote hello world. Now, to be fair, there's still some syntax there. There's parenthesis, there's double quotes, but I dare say this is the easiest of the versions to write, but Python itself is nonetheless very powerful. It's just the humans that invented it and have evolved it over time have tried to make it read as much like English as is possible with one of these programming languages. So if you're curious to see what other programming languages exist in the wild, you can actually go to Wikipedia to such URLs as this and you'll see dozens, hundreds, someday even thousands of programming languages via which you can write not just hello world but any other program. And in fact, if you're curious to see Hello World specifically, at this website here is a massive list of implementations of Hello World in bunches of languages. In fact, it's kind of a fun way to get a quick sense of what other languages look like, albeit for implementing something relatively simple like printing to the screen. All right. So, if we now have source code at our disposal in any of these languages, but soon we'll focus indeed on Python, how do we actually get the computers to understand that source code if again all they understand at the end of the day is machine code, the underlying zeros and ones? Well, there's a few different paradigms that the world has had over the years to achieve precisely that goal. For instance, if we draw a an abstract drawing here with the CPU, the computer's brain or central processing unit all along the bottom here. I got three columns ready to go here because I'm going to propose that we consider three different ways of getting source code to be understood by computers. Why? Well, again, it's a lot more fun and pleasant for you and I to write code in Python, it would seem, than in machine code, zeros and ones. So, how can we get from one to the other? Well, one common paradigm is to do this. You need to get to machine code at the end of the day because that is what under is understood by the underlying CPU. But you and I again would like to focus on writing source code. So how do we get from source code to machine code? Well, years ago humans uh invented if you will wrote software called a compiler. And there's many compilers in the world but at one point there was one first compiler and its purpose in life was simply to translate one language into another. In this case, it might have translated the source code, for instance, written in C into the underlying machine code, zeros and ones. And compilers really more broadly just convert one language to another. So we can convert among all of the languages we've discussed thus far down to assembly language, down to those zeros and ones. Their purpose in life really is to make your life and mine easier, allowing you and I to think at and write code at a fairly high level of abstraction, if you will. give me print hello world on the screen without having to worry about the underlying zeros and ones. Someone else smarter than me put in the time to write code that implemented a compiler so that I can just run the compiler by like double clicking an icon or typing some command in my computer to convert my source code into machine code. And the upside of this is that even though it might take a moment, a second, a few seconds, maybe a few minutes for massively large projects to convert source code to machine code, once it's saved as zeros and ones, it's going to be really fast on my Mac, my PC, or my phone. And in fact, this is the paradigm that C still follows. And C, even though it's an older language now by decades, still incredibly omnipresent because it fits in nicely to this model of compiling down to very fast zeros and ones. Moreover, you can leave it to the computer scientists of the world and the software developers to write really good code for the compiler itself so that the compiler turns even your messy code, your inefficient code into something even faster underneath the hood. Now, that's not the only way because I'll claim that it's a little annoying to have to write your code, compile your code, run your code, make a change to your code, recompile your code, run your code, and repeat and repeat. It's just another step. And indeed, if it takes a few seconds, it just gets annoying over time. So, there's other models that some languages tend to follow whereby you and I can write source code, but we don't bother converting it to machine code per se. We just feed it into an interpreter. And an interpreter is just another piece of software that's been designed to understand a language top to bottom, left to right, if you will, and understand and interpret what it wants you to do. So, if it sees print, it's going to print on the screen. If it sees move, it's going to move something around in memory. If it sees uh uh save, it's going to save a file to disk. In other words, the interpreter is just going to translate much like a human interpreter translating between two spoken human languages converts one input to a corresponding output. And long story short, this model just tends to be convenient if nothing else because you can write your code and then interpret your code, that is run it straight away. You can change your code, you can reinterpret it, that is rerun it. So you you eliminate this sort of middle step. But there's going to be a trade-off as is always the case. interpreting a program tends to be slower than actually compiling a program and then running it. So it indeed might depend on your goals which you want to optimize for. And yet increasingly we have this third model that we'll look at here whereby you and I get to write source code. We run it through a compiler and that compiler converts the source code into what we'll generally call byte code. And bite code is just an intermediate representation. It's not really zeros and ones, but it's closer to zeros and ones, if you will, which just means it's even easier to take it that final mile and get it into the zeros and ones that the machine expects. But what you do is you actually feed that bite code not directly into the CPU, but into what's generally called a virtual machine. A virtual machine might be something you're familiar with in the corporate world for instance whereby you might have familiarity with products like VMware and similar where you can run Windows on a Mac or you can run multiple operating systems on the same computer or you can connect to a remote desktop somehow or other. But virtual machines are very commonly used even on laptops and desktops and phones and other devices to take as input bite code that someone else uh outputed in an intermediate representation not quite zeros and ones. And those zeros and ones are understood by the virtual machine. And the virtual machine is just always running in this case on the CPU. And so it's effectively interpreting the bite code. And here's where we won't get too lost in the weeds because all of these models do have some overlap. I'm seeing I'm using interpreted and compiling sort of both in this middle column. But what's nice about this middle column, which is increasingly common, is a lot of these steps are automated. So you don't actually have to manually compile your source code into bite code. You just run your code with some command or some click of a button and all of this just kind of happens automatically. Moreover, what often happens too is the bite code is cached that is saved somewhere on your hard drive or maybe in the cloud so that the compilation step doesn't have to happen again if you haven't actually changed the source code. So in short, what you're really seeing in this simple picture alone is the evolution of programming paradigms over the years where humans and businesses have realized, hey, how can we speed up our code when it's running and how can we speed up the writing of the code before we even run it? And so you're seeing an evolution of how these all work. And indeed AI is just one another level of abstraction on top of this whereby you don't even write the source code. you could just say the English or some other human language and then somehow or other all of these other steps would seem to happen automatically underneath the hood for you. So today we're going to focus primarily on Python, a very popular and relatively simple programming language. The goal is again not to make you completely comfortable with the language but with the ideas that it implements because the ideas that Python implements and offers to you and me as programmers is generally representative of features you would see in many other programming languages as well. And indeed this is the case in general for software engineers. You might take a course in learning some programming language. You might study a particular programming language and then another and then another. But at some point you just start to teach yourself new languages as by reading documentation or asking some AI or asking some colleague or looking at other examples because once you've seen a range of programming languages maybe Python among them you'll start to notice patterns similar paradigm similar features and even though the syntax the text that you type looks a little different most of that is not intellectually interesting it's the ideas underlying it that are and indeed we'll focus today primarily on the ideas while still having some fun with the code itself along the way. So, this is what I want to write as my very first program. And printing out hello world to the screen is sort of every programmer's first program canonically. But how can I actually make that happen? Well, of course, I've just typed it on the screen here in a slide, and that's fine. But I should really be typing it in a better place, a program that's designed to actually understand what it is I'm typing, not just display it. And a very popular tool for just that nowadays is called Visual Studio Code. It's largely open- source software backed by uh Microsoft that is increasingly popular not just to develop for Windows computers but Macs for Linux devices for phones. It's a very popular text editor so to speak that shares features what are generally called integrated development environments or idees because if you add in lots of plugins and lots of other features this program in particular can do a lot for you and there are many alternatives and you can certainly use any number of the alternatives but we for this course will provide you with a cloud-based version thereof if only so that you don't have to deal with the inevitable technical support headaches of trying to install something configure it getting it to work on your computer and your version of an operating system often tends to get in the way of actually learning the interesting stuff. So, we'll get you started as in the courses assignments with a cloud-based version that just works, but you can also download for free tools like Visual Studio Code onto your own Mac or PC and actually get it up and running locally without any need for internet or the course's own infrastructure. And this is what we're about to see, a screenshot thereof. This is Visual Studio Code as it might look if you have created a file called by convention hello.py.py.py indicates that this is a file that's just text but that's written in a language called Python. And other languages like C might use a C file extension. Languages like Java might use Java and the like. So Py is for Python. Now there's essentially one two three four main components of the screen here. So, at the left is the so-called activity bar, which is essentially the menu where you have bunches of icons. This one being the file explorer that let you access different features of the software. I'll generally hide that on my computer just to free up some space, but you'll see it by default. Over here is the so-called explorer, which shows you all of the files in your account. Now, when I took this screenshot, I had already created one such file called hello.py, and that's why we see it right here. When you first fire up VS Code for short, aka Visual Studio Code, you might not see anything in that window or you might see even more depending on how you start the software. Now, up here is the actual file I created. It has a tabbed interface just like today's browsers do. And you have print hello world there in that file. A single line of code on line one. Now, notice it's colorcoded. This is purple. This is blue. And then the rest of it is black. That's not something I did manually. This isn't a word processing program like Microsoft Word or Google Docs or the like where I highlighted things and then chose a color from a menu. This is what's called syntax highlighting. And this is one of the features of software like VS Code, again, Visual Studio Code, whereby it knows this is a Python file because I told it in the file name. And because programming languages are standardized with certain keywords and certain punctuation or syntax, it knows that print is going to be soon what we're going to call a function. and the blue parentheses are pure syntax that make clear what it is we want to print to the screen. So more on that and more colors to come. Now down here lastly is the most esoteric feature of VS Code and really programming environments in general known as a terminal window. This gives you a prompt here represented as a dollar sign. Sometimes it looks like a hash symbol or it can be anything else but we'll standardize on a dollar sign here. And this is essentially where your cursor will just be waiting and blinking. waiting for you to type a command. Because what you're seeing down here is generally what's known as a command line interface or CLI. And even though this might seem a step backwards, maybe reminiscent for some of you of the old DOSs days before there was Windows, it turns out that it's wonderfully useful and wonderfully efficient to be able to type commands to get work done quickly as opposed to clicking on menus and dragging icons, which is fine, which is certainly much more userfriendly, but doing things at the keyboard for many, dare say most programmers just tends to be faster and more productive by spending a lot more of your time in a command line interface or CLI. So the terminal gives you just that, a CLI. This whole thing though of course is graphical in nature, a graphical user interface or guey for short. So you'll see here I haven't actually hit enter yet, but I've typed out at my prompt python spacehello.py and I'm about to hit enter before I took this screenshot. Now what have I typed here and why? Well, this is clearly the same name as the file hello.py. And here I am saying the word Python explicitly. Well, it turns out by design and a little confusingly the program you use to run a program written in Python is also called Python itself. So if you think back to that mental model from a moment ago, Python is the name of the interpreter that we are using in order to run my code ultimately. Now that too is a bit of a simplification because there's still going to be a virtual machine involved typically when you install Python on a system. But I think that's the simplest way to think about it. Python is the interpreter that's going to read my code top to bottom, left to right, and interpret what I mean and what the computer should do in response. All right, so let's go about doing this. Instead of a screenshot, I'm going to open up the cloud-based version thereof, and I'm going to put it into dark mode just so that the code pops a little bit more on the screen. And the only thing that's different about my interface right now is that in advance I've downloaded some code for this lecture specifically in a source three folder aka directory at top left. So in my file explorer I have source three and then the name of my unique code space here as these things tend to be called. Um but your number or your code space might be somewhat differently named but for the most part your interface will look largely the same. You might have some more icons, some more buttons, some more features. I've actually turned off as much as I can to actually simplify things. And in fact, I'm going to go ahead and hide my so-called activity bar. And I'm going to go ahead and hide my explorer so as to really distill our screen here into the absolute minimum room for the code I'm going to write in those tabs and my terminal window at the bottom so I can run it. And sometimes at least if my code gets long, I might even hide the terminal just so we can focus on the code alone. But with a keyboard shortcut, all I'll pull it back up just as you might at home ultimately too. So, how can I go about writing my first program? Well, what I'm going to do here at the bottom of the screen is run code space hello.py. Now, I'm going to go ahead and hit enter. And what I'm going to see here is a blinking prompt next to the line number one. Now, that number is not actually in the file. That's just VS Code being helpful in numbering my lines for me automatically. Now, we saw already multiple times what this program should look like. So, let me repeat that. print parenthesis quote unquote hello, world close quote there at the end to be clear. Now, VS Code's trying to be helpful. It's starting a second line for me even though I haven't moved the cursor there. And that's fine. You'll find that these text editors and idees or integrated development environments more generally not only give you features like syntax highlighting, color coding things for you, they also sometimes try to anticipate what it is you're about to type. And in fact, what I've done is also in advance try to disable as many of those features as possible really to focus on developing today some muscle memory and some instinct for what you should type not just let the computer or AI type for you longer term once you actually have your footing with Python or any programming language I think it's good to actually enable features that empower you to be all the more productive be it AI or otherwise but for now we're going to focus indeed on these fundamentals so that's it the file has saved itself self uh by design automatically because that's how we've configured VS Code here. And now it's time to run the program. Now there's different ways to run programs. Sometimes you can click a little play icon if you want or you can actually do it in a command line interface. And again to develop some muscle memory today and to really emphasize the steps that are happening writing code and running code, I'm going to tend to use my CLI command line interface or terminal window down here. So I just ran a moment ago a code command followed by the name of the file that I wanted to code. That is write that's specific to VS Code. Has nothing to do with Python per se. But again, I've standardized on the file name ending in.py. If I want to now interpret this program and have it say hello world to me, I can do this. Python space hello.py enter. And voila, I've just written and run or executed my very first Python program. Of course, it's only ever going to say hello world. If I run Python of hello.py again, it's going to give me exactly the same output. Now, it's fun the first time, sort of mildly interesting the second time, diminishing returns thereafter. Let's make this program more interesting by introducing another function there, too. Because we've seen already that print is apparently a function. Indeed, it's a call to action. And it's a verb that apparently the Python interpreter understands because that's how it printed out hello world on the screen. But it'd be nice if it could do more than just print out hello world, hello world again and again. Well, let's introduce another function that comes with Python itself. And you would only know this by taking a class, reading a book, reading up on some online resource on what functions come with a language. I'm going to go back over to my terminal window here. I'm going to clear my terminal just to keep things a little clean, but that's just erasing the commands I previously wrote. Now, I'm going to go ahead and introduce another feature to this same program. I'm going to go ahead and first delete what I wrote earlier, just because I think we're past that. I'm going to zoom in a bit more just so you can see this a little more clearly. And what I'm going to do now is go ahead and type input, which is going to be the name of a function that indeed comes with Python. I'm going to use quotes inside of these parenthesis to then prompt the user with a question. For instance, if I want to prompt the user, say for their name, I could say, "What's your name?" question mark. I'm going to leave a space at the end so that the cursor moves over ever so slightly. Then I'm going to go ahead and print out quote unquote hello, comma. Then I'm going to go ahead and print out at the bottom, huh, what do I print? Well, maybe it's David who's going to run this program. So maybe I could print out quote unquote David as the answer to that question, but that doesn't really make sense. The whole point of this program, I claim, is to make it more dynamic and more interesting than just hello world, and certainly more interesting than hello David, hello David, and the like. So what I'd like to propose is that this input function, which I claim is going to ask the user that question, I'm going to make sure that I save the answer to that question somewhere. And I'm going to type something like this. name equals input parenthesis quote unquote what's your name and this equal sign is actually something you shouldn't think of as equality as much as you should assignment in programming languages like Python this equal sign means do whatever's on the right hand side first and then copy that value from right to left and store it in this thing here now what's this thing I came up with this word myself but it makes sense because I'm prompting the user for their name I could have called this thing anything I want because it's a variable. A variable is a storage container for a value, be it a piece of text or something else. I could indeed call it anything I want. Mathematicians like X's and Y's and Z's, but it would be a little less clear to the reader and to me tomorrow or a few days from now what it is that's in that variable if I just call it X or Y or Z. So, by convention, stylistically, it's good practice when programming to give your variables good names. And that just makes it clearer to you, the writer, and to future people, the readers thereof. Now, on line two, I've gotten ready to say hello, so I've got my English grammar set up. Now, what I can do down here is call print again and pass to it another input, which is going to be the variable itself, named however I saw fit. What's going to happen now at the end? If I go ahead and run Python of hello.py pi again and hit enter. Now I'm not going to see hello world. I'm going to see what's your name and a space and then my cursor where I can type my name. So now I'm going to go ahead and type in for instance David. Enter. And I'll be greeted with dynamically hello, David. If someone else were to walk up to the keyboard and run this program again, Python of Hello.py, perhaps it's our old friend John Harvard. Well, John might type in his name and then hit enter. And now we see hello, John. So what we've seen here are not only variables but what we're going to call arguments. Arguments are inputs to functions that alter their behavior. And syntactically the way you provide an argument to a function is just as we have now several times inside of those parenthesis after the function's name you provide the input there too. Quote unquote hello world quote unquote what's your name or no quotes and the name of a variable. Indeed, those quotes are clearly now important. When you just want to use English or some other human language and have that display on the screen, you need to encase it in quotes, double quotes as I did. You can also use single quotes if you prefer, so long as you don't have any apostrophes or things that might confuse Python thereafter. But if you provide those inputs in quotes, that makes clear to Python that, oh, you want me to print out this whole thing, and it won't confuse that input for what could actually be a variable instead. In fact, I did not use the quotes around name because again, name is a storage container for the value the user previously typed in. So, I want print to print out the value of that variable, not quote unquote name per se. But I do think and I admit the aesthetics here aren't the prettiest. In fact, you can see hello, John, on two separate lines, which isn't all that elegant. Let me go ahead and propose that we kind of clean this up sort of visually on the screen. And we can do this in a few ways. And let me propose one of the simplest first. If I want to keep the hello, John and the hello, David on the same line, let me change my code a bit. Just for clarity, I'm going to clear my terminal window just to hide the previous commands. I'm going to get rid of line three altogether. And then up here inside of the parenthesis on line two, I'm going to use the plus operator, so to speak, the plus sign as we know it from math. And then I'm going to go ahead and type the variable name there. Now my program's a little shorter, but it's actually a little better as follows. Let me go ahead and now and run Python of hello.py and hit enter. I'll be prompted again for my name. So I'll type in David. Enter. And I think I should see on one line ah so close. Hello, David without a grammatical space in there. So I think that's an easy fix. And in fact, it stands to reason that the f the it stands to reason that the space is missing because I didn't tell the computer what to do. And here is just the simplest, stupidest example of why precision is so important in programming. The computer is meant to do exactly what you tell it to do. And unlike pseudo code, and unlike humans who might read that pseudo code, who might read between the lines, so to speak, and make certain assumptions about what you mean because you're just they're just a reasonable person. The computer is only supposed to do and is only designed to do exactly what you tell it to do. So if you omit the space, as I did, it's not going to give you a space. So that's fine. And I'm going to go ahead and hit the space bar now inside of the quotes. No other changes. I'm going to rerun Python of hello.py and hit enter. Type in my name again. And now we're back in business. Hello, David. Exactly as I intended it all this time. Well, what more could I do here? Well, it turns out that some functions take multiple arguments and print is one of them. We've seen that we can pass uh print one argument and that was true of the input function too. But what's nice about print is that you can pass in two arguments, three, four, more, even zero if you really want. So, let me go ahead and do just that. Let me go back to VS Code here and point out that what's been happening thus far is this plus operator is doing something for which we have a term of art. It's doing concatenation. Concatenation is the joining of two pieces of text. One on the left, one on the right. And the one on the left is clearly text because it's in quotes. The one on the right is the value of the variable which we know is going to be text like D-av or jon for either of our names. And so this concatenation operator is doing this. It's taking hello. It's taking the name joining them together. That is concatenating them together. And that is the argument that print is receiving as input and therefore displaying on the screen. But because I've read the documentation, I can actually uh change this to pass print two arguments and maybe just kind of clean this up a little bit. Let me go down to my terminal here, run Python of hello.py. Now notice there's no plus operator, but there is another comma. Hit enter. What's your name? DAV ID. And uh so close. Now again, the computer is taking me very literally. Why? Well, I still have the space here, but it turns out if you dig into the documentation for the print function, you'll see actually that when you pass in not one but two arguments to the print function, you'll get a space for free. It is designed when you pass in two or more arguments to separate them by default with a single space. I would only know that from having been told it, reading the documentation or the like. So, that's fine. I can fix this by reverting to the original version because now I'm getting the space automatically by nature of how the function works. So if I run this one more time, Python of hello.py, enter, type in my name, David. Now it looks exactly as I intend. And all we're doing now is demonstrating that you can have not just one but two or three or it turns out is we'll eventually see even zero arguments as well. All right. So how would you know any of that? I keep referring to the documentation. Well, among the nice things about Python, is that it is actually very thoroughly documented. And if you go to this URL here, you can see the official documentation for Python, which actually evolves over time as the language itself evolves and gains new features and therefore newer version numbers as well. And I took a look at that documentation. At some point, I'm like, oh, the print function does take multiple arguments if I so choose. And that's how I knew to do that. In fact, I also know as a result that I can do this, too. If I want to move the printing of the name to its own line, I can do that. I didn't have to abort altogether what was my line three. If I would really like to pass in name as the variable to as the argument to my function print, that's fine. But recall that previously this did not work out well for us where I simply had the space and then nothing after it because it put hello here and then the name David or John on the second line. But if I read the documentation I'll actually see that I can pass in another type of argument to the print function too. I can use my comma again. I can say end equals and for instance quote unquote because it turns out again per the documentation the print function will end every line of text automatically with a new line. And we actually glimpse this ever so briefly in the assembly code earlier it turns out in programming the way you express a new line the hitting of the enter key or the return key on your keyboard is you sometimes don't have to hit it. You can textually write a backslash and then a lowercase N. And Python and other languages know that, oh, the human wants me to move the cursor to the new line, the next line below it. By default, the documentation for print says exactly this, that the line will end by default with backslash end. That's why the cursor gots moved and made hello, David, and hello, John kind of messy. But if I override that and say, "No, no, no, no. end each line with nothing quote unquote with nothing in between. I can change that behavior too. Let me go ahead and run Python of hello.py again. Type in my name and it's not going to be that exciting an outcome. It's still going to look the same way, but it's going to achieve the exact same result yet another way. And this too is thematic in programming whereby simply by writing code in different ways, you can in fact achieve the same outcome. Not unlike in English where you can express the same idea in different ways using different nouns and verbs and the like. Some of them better some of them worse. But in code here we can indeed achieve and solve the same problem in many different ways. Now, over time, and if you study programming and aspire to be a software engineer, you'll learn that there are in fact better ways to write some code because not only is code evaluated typically on the quality of its style, like your choice of variable names and whether or not it's pretty to read and you've used whites space, that is spacebar characters in appropriate places. Well, it stands to reason that it's got to be correct. Otherwise, what's the point of writing it if you're not actually solving the problem correctly? But design is another seemingly subjective measure of code quality. And in fact, this is why a lot of companies in the real world actually have what are called code reviews whereby when you write code that you want your company to use in its product, typically there'll be another human or nowadays an AI that at least gives you some qualitative feedback on it and says you could maybe do this a little better. It will give you suggestions. It might approve or even deny the submission of your code to the system. So writing good code is not only correct but a matter of design as well. Now what we're seeing here in my code is a use of arguments indeed. But the first of these arguments is what we're going to now refer to as a positional parameter. It is an argument that has meaning because it came first in this case if you will. This argument though is what we're going to generally call a named parameter. The word end exists because the human who invented the print function in Python decided that there will be a parameter whose name is en the value of which by default is back slashn the new line character but that we can change in this way. So this is a long way of saying that Python supports not only what we'll call positional parameters but also named parameters as well. And this is a bit of a subtlety but when you know a function takes inputs it is said to take parameters. When you actually use those parameters by passing in values, you're passing in arguments. So when you invent the function, they're called parameters, but when you use the function, they're called arguments. But for the most part, they refer to one and the same thing. And humans will often slip and use them interchangeably as well. Now, let me go back to my code here and propose that we can solve this yet another way. In fact, maybe the best way, if you will, or the most conventional way. Let me clear my terminal here and let me go back up to this line of code and line three and get rid of both and propose that we actually do all of this in one elegant line. I'm going to go ahead and print quote unquote hello, and then let me just print out the person's name like this. I like this because it's keeping everything on one line. I've got the hello comma. I've got the variable's name. Let's go ahead and run it. Python of hello.py. Enter. DAV ID. Some of you might see already where this is going. And even if not, think for just a moment about what I might have done wrong on line two. You're about to see the first probably many bugs, mistakes in software, intentional or otherwise, because when I hit enter now, I'm not going to see hello, David. I'm going to see literally hello, name. Now, that stands to reason because I literally put n inside of those quotes. But there is a way to fix this. It turns out, and this is a newer feature of Python, I can put in curly braces as they're called, the name of that variable, which coincidentally is name, but again, I could have called it X or Y or Z. That just would have been bad style. But I now need to make one other change because if I run this version of the program and type my name, Python's still going to take me literally and this time weirdly print out hello, name in curly braces, I need to tell Python that this text is actually a little bit special. And I want it to format the text for me. I want to go ahead and specify before the double quote here a letter F. Notice that the curly braces actually changed color because VS Code knows what I'm up to. So now I'm going to run this a third time. Python of hello.py. Type in my name. And now I get hello, David. So this is a very subtle detail. This f that I'm putting before the string. And frankly, after programming all these years, I think this is a weird looking feature. It still feels very unnatural to me to squeeze a letter F in between the parenthesis and the quote. But this is a feature that's been adopted for some time and is the way that you can use what are called format strings in Python. Now what more can we do with this program? We can actually now that we have some of these basics in mind. We can actually kind of add more features still. Let me clear my terminal window here and let me propose that if I run this a bit lazily, maybe with my caps lock key on, I might do something silly like this. We all kind of know someone in our lives that tends to write in all caps. Um, this just looks bad. And in fact, if this isn't a silly little program, but is maybe a form on a web page from which I'm collecting data from users, like I don't want some users names capitalized properly, some all uppercase, some all lowercase. It would be nice to maybe canonicalize, standardize what the capitalization of these texts are. So, I can actually do that in a few ways and also solve other problems. For instance, suppose I'm really difficult and when I run this program, I weirdly type the space bar three times and then I type in my name and then I hit the space bar again and mail. So, not that I would do this, but you'd be surprised. We collect a lot of data for this course and others. So many people weirdly hit the space bar before they start typing or after. And what this is going to do in this case is kind of mess up the appearance of this when you spit it back out with the print function. So, I can clean up some of these mistakes pretty easily. Let me actually go up to uh my code here. Let me actually specify the following. Um let me go ahead and give myself another variable. We'll call it new name, but I'm going to clean this up further, too. I'm going to set this equal to the name function. Uh the name variable, but I'm going to go ahead and use a dot and the word strip and then two parenthesis. This is another function called strip that weirdly for now you call that is invoke or use by using a dot on whatever value you want to strip whites space from. And by whites space I mean the space bar, the tab key or certain other characters as well. But this is going to get rid of spaces to the left and to the right of what the human typed in because this is going to partially clean up that mess. If I run Python of hello.py pi type in space space space space David space space space space space space space space space space space spacespace space space space space spacespace space space space mail and enter notice that huh nothing happened here but this two stands to reason and I didn't intend to make this mistake this stands to reason why because the name variable I'm printing is still called name if I want to print out the new variable name I want to change what's in the curly braces to new name and to be clear what's happening on line two is a little new but not entirely new the strip function here is new and it's operating on this variable called name. But the equal sign is not new. That's the assignment operator. That means copy from the right the stripped version of the name over to the left. And the thing on the left now is another variable whose name I invented. I could have called it X or Y or Z, but I gave it a slightly better name than that. And now on line three, I'm using that variable's value. Let me g
Original Description
This is Lecture 3 of CS50 for Business on Practicing Programming. Learn fundamentals of Python programming with practical examples of functions, conditionals, loops, data types, libraries, and real-world applications.
To take this course for a certificate, register at cs50.edx.org/business.
***
This is CS50, Harvard University's introduction to the intellectual enterprises of computer science and the art of programming.
***
HOW TO SUBSCRIBE
http://www.youtube.com/subscription_center?add_user=cs50tv
HOW TO TAKE CS50
edX: https://cs50.edx.org/
Harvard Extension School: https://cs50.harvard.edu/extension
Harvard Summer School: https://cs50.harvard.edu/summer
OpenCourseWare: https://cs50.harvard.edu/x
HOW TO JOIN CS50 COMMUNITIES
Bluesky: https://bsky.app/profile/cs50.harvard.edu
Discord: https://discord.gg/cs50
Ed: https://cs50.edx.org/ed
Facebook Group: https://www.facebook.com/groups/cs50/
Faceboook Page: https://www.facebook.com/cs50/
GitHub: https://github.com/cs50
Gitter: https://gitter.im/cs50/x
Instagram: https://instagram.com/cs50
LinkedIn Group: https://www.linkedin.com/groups/7437240/
LinkedIn Page: https://www.linkedin.com/school/cs50/
Medium: https://cs50.medium.com/
Quora: https://www.quora.com/topic/CS50
Reddit: https://www.reddit.com/r/cs50/
Slack: https://cs50.edx.org/slack
Snapchat: https://www.snapchat.com/add/cs50
SoundCloud: https://soundcloud.com/cs50
Stack Exchange: https://cs50.stackexchange.com/
Telegram: https://t.me/cs50x
Threads: https://www.threads.net/@cs50
TikTok: https://www.tiktok.com/@cs50
Twitter: https://twitter.com/cs50
Twitter Community: https://twitter.com/i/communities/1722308663522594923
YouTube: http://www.youtube.com/cs50
HOW TO FOLLOW DAVID J. MALAN
Facebook: https://www.facebook.com/dmalan
GitHub: https://github.com/dmalan
Instagram: https://www.instagram.com/davidjmalan/
LinkedIn: https://www.linkedin.com/in/malan/
Quora: https://www.quora.com/profile/David-J-Malan
Threads: https://www.threads.net/@davidjmalan
Watch on YouTube ↗
(saves to browser)
Sign in to unlock AI tutor explanation · ⚡30
Playlist
Uploads from CS50 · CS50 · 0 of 60
← Previous
Next →
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
Hello, World: Hadi Partovi
CS50
Content Distribution and Archival in a Digital Age
CS50
CS50 2014 - Week 1
CS50
CS50 2014 - Week 3
CS50
CS50 2014 - Week 0, continued
CS50
CS50 2014 - Week 4
CS50
Week 3, continued
CS50
Quiz 0 Review
CS50
CS50 2014 - Week 3, continued
CS50
CS50 2014 - Week 7
CS50
CS50 2014 - Week 7, continued
CS50
Breaking Through The (Google) Glass Ceiling by Christopher Bartholomew
CS50
Introduction to Amazon Web Services by Leo Zhadanovsky
CS50
CS50 2014 - Week 9
CS50
How to Build Innovative Technologies by Abby Fichtner
CS50
Light Your World (with Hue Bulbs) by Dan Bradley
CS50
Building Dynamic Web Apps with Laravel by Eric Ouyang
CS50
CS50 2014 - CS50 Lecture by Steve Ballmer
CS50
CS50 2014 - Week 10
CS50
This is CS50 with Steve Ballmer?
CS50
Meteor: a better way to build apps by Roger Zurawicki
CS50
Data Analysis in R by Dustin Tran
CS50
Data Visualization and D3 by David Chouinard
CS50
CS50 2014 - Week 6
CS50
Build Tomorrow's Library by Jeffrey Licht
CS50
CS50 2014 - Week 9, continued
CS50
Essential Scale-Out Computing by James Cuff
CS50
iOS App Development with Swift by Dan Armendariz
CS50
Sam Clark Leads Yale Students on Tour to CS50 at Harvard
CS50
3D Modeling and Manufacture by Ansel Duff
CS50
CS50 2014 - Week 5, continued
CS50
hello, world
CS50
CS50 2014 - Deep Thoughts - Hash Table
CS50
CS50 2014 - Deep Thoughts - Binary Tree
CS50
CS50 2014 - Deep Thoughts - Scratch
CS50
CS50 2014 - Deep Thoughts - MySQL
CS50
LaunchCode Visits CS50
CS50
CS50 Live, Episode 100
CS50
CS50 Field Trip to Google
CS50
This is CS50 AP
CS50
Week 4: Monday - CS50 2011 - Harvard University
CS50
Week 2: Wednesday - CS50 2011 - Harvard University
CS50
Week 1: Wednesday - CS50 2011 - Harvard University
CS50
Week 11: Monday - CS50 2011 - Harvard University
CS50
Week 3: Wednesday - CS50 2011 - Harvard University
CS50
Week 12: Monday - CS50 2011 - Harvard University
CS50
Week 1: Friday - CS50 2011 - Harvard University
CS50
Week 3: Monday - CS50 2011 - Harvard University
CS50
Week 10: Wednesday - CS50 2011 - Harvard University
CS50
Week 2: Monday - CS50 2011 - Harvard University
CS50
Week 9: Monday - CS50 2011 - Harvard University
CS50
Week 7: Monday - CS50 2011 - Harvard University
CS50
Week 5: Monday - CS50 2011 - Harvard University
CS50
Week 5: Wednesday - CS50 2011 - Harvard University
CS50
Week 7: Wednesday - CS50 2011 - Harvard University
CS50
Week 8: Monday - CS50 2011 - Harvard University
CS50
Week 9: Wednesday - CS50 2011 - Harvard University
CS50
Week 8: Wednesday - CS50 2011 - Harvard University
CS50
Week 10: Monday - CS50 2011 - Harvard University
CS50
Week 2: Wednesday - CS50 2010 - Harvard University
CS50
More on: AI Pair Programming
View skill →Related Reads
📰
📰
📰
📰
Fable 5 Costs 5x More Per Task Than Grok 4.5. Here’s Whether That Actually Matters.
Medium · AI
Why Modern Test Automation Frameworks Need AI in 2026
Medium · Programming
If AI Writes Your Code, Why Learn Python?
Medium · AI
Stop Hallucinating Terraform: Building a Private Internal Developer Portal with RAG and Gemma 2
Medium · AI
🎓
Tutor Explanation
DeepCamp AI