Python is a computer programming language used by major companies like NASA, Reddit, and even Google. The creator of Python, Guido van Rossum, named the language after his favorite TV show: Monty Python’s Flying Circus!
Python is more concise than other languages and it is text-based, which makes it easy to read, write, and understand. Because of this, many professionals consider it the perfect first programming language for beginners. It is also an incredibly versatile skill to have when entering the job market. Skills in Python can set you up for careers in areas like data science, web development, and artificial intelligence development.
While it might seem like high school students are too young to learn Python, there is no better time! Below, you will find plenty of resources for young people who want to learn Python. There is no shortage of benefits to starting this journey before going to college. Learning Python early in life can be a great foundation for future learning, employment, or just a creative and unique hobby to keep your brain active.
Books and Online Resources
There are a tremendous number of resources available to help young adults (down to elementary schoolers!) learn Python. Because Python is typically thought of as an easier language to learn, it is a great introduction to programming languages in general.
While there are plenty of online games and activities for students to learn Python, research suggests that reading still plays an important role in knowledge acquisition. Books allow children the freedom to skip chapters and flip around a book to get the information they need. Students can also read much faster than a person can talk, making reading an efficient way to receive information. Here is a list of a few books to get your collection started:
- Adventures in Minecraft: This book is geared toward children aged 11-15, so it’s best suited for high school freshmen at most. However, if you enjoy Minecraft, this book will teach you how to recreate your gaming experience by being able to program your interactive world.
- Python for Teenagers: Learn to Program like a Superhero: This book gives students fun and easy-to-follow examples that guide them through the fundamentals of Python.
- The Python Guru and Think Python 2e: These are eBooks available for free download, but students are encouraged to print them out to take notes and easily access certain sections of the book when needed.
Outside of physical books and eBooks, there are several other resources available for high school students who want to learn Python. Universities like MIT and Harvard have free lectures available on YouTube for students who are more auditory learners and want to teach themselves concepts from scratch. Finally, Python Central offers many free resources for beginners, including eBooks, video lectures, and tutorials.
Learn Python in NextGen’s Summer Classes
If learning Python in a classroom setting appeals to you, NextGen Bootcamp offers several different Python classes for high school students. Classes can be taken in-person at its Manhattan campus. There are also convenient remote Python classes available that can be attended virtually from anywhere in the world. NextGen courses boast small class sizes, expert instructors, and offer free retakes within one year of the original course date. They are suitable for beginners, though all attendees should have a basic understanding of computers.
The in-person Python classes at NextGen Bootcamp include a two-week Data Science Summer Program designed for beginners who want to learn more about analyzing large datasets. There is also a Web Design Summer Camp that teaches students to design and implement their own completely functional website in just two weeks. Showcasing a website you made can be a great addition to applications for scholarships, internships, and college admissions.
If virtual learning is more suitable for you, there are plenty of options in this category as well. NextGen Bootcamp offers a Python Data Science course that specifically prepares students to use Python in data science applications like artificial intelligence and machine learning. This course takes place on weekdays during the summer for three hours per day for a total of 45 hours. There is also a Computer Science Summer Certificate program, which includes the fundamentals of both Python and Java. This course is 95 hours long and lasts three to four weeks.
Python Career Paths
Proficiency in Python can open the door to a wide range of career opportunities depending on your other interests and skills. The US Department of Labor estimates that over half a million new jobs will be created in this area in the next decade. As the world becomes more digitized, programming with Python is no longer limited to computers. Python can be used to develop various household devices, down to lightbulbs and refrigerators! As technology continues to diversify, so too will the job opportunities that require skills in Python.
If you consider yourself a more curious and analytical person, data science may be a path you want to explore. These professionals help businesses in nearly every industry analyze data to answer questions and provide solutions to the biggest challenges they are facing. Data science is one of the most common careers that utilizes Python, and it’s also one of the most lucrative: Data Scientists make an average annual salary of nearly $100,000.
If you enjoy being more creative, you can apply your Python knowledge to a career in web development to build websites and apps. This is another career involving Python that is growing quicker than average and, according to the US Bureau of Labor Statistics, offers an average annual salary of around $77,200 per year.
A final career option that requires extensive Python programming knowledge is in artificial intelligence (AI) and machine learning (ML). This field is becoming more necessary as work demands increase in complexity and are no longer able to efficiently be done by humans. For example, AI is being used in the Department of Defense to identify potential threats for both civilians and in cyberspace. A human could not analyze such a large amount of data at once, but AI does not have the same limitations. Artificial Intelligence Engineers are offered a wide range of salaries, but they are typically over $100,000 annually.
Video Transcription:
[MUSIC PLAYING] DAVID MALAN: This is CS50 and this is lecture 6. And you'll recall that last week we introduced web programming by way of HTML and CSS, or at least the building blocks because we don't actually have the ability to program yet. It's just markup, HTML and CSS with stylization 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? AUDIENCE: An IP address. DAVID MALAN: 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. It was like two minutes ago. OK. Yeah. AUDIENCE: A port number. DAVID MALAN: A port number. So another number, shorter number, that's just a number like 80 or 443 referring to 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 www.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?
AUDIENCE: A specific web page. DAVID MALAN: A specific web page. And someone else, which web page specifically, presumably? AUDIENCE: Index. DAVID MALAN: 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 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 interesting work, ultimately. And so this slash search indicates some kind of software running on Google servers as of last week that's simply responds to requests. And what did question mark q equals cats do or represent in that demonstration?
AUDIENCE: User input. DAVID MALAN: Yeah, user input. So the question mark just says, that's it for the file name or the URL. Here comes the user's input. Q is just literally the HTTP parameter or input that Larry and Sergey, founders of Google, 20 years ago decided would represent the user's input, q for query. Equal just means that query that the human typed in was cats. 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 www.google.com/search?q=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 OK. 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 other humans what that numeric code is, I mean, that is an uninteresting detail. But the world, for whatever reason, has revealed in many web sites 404.
But it just means the same thing. Everything is not OK. A file was not found. You might see something else like this. We saw this with Harvard, in fact, curiously, that Harvard had moved permanently. Now, Harvard was responding to certain queries with HTTP 301s in order to achieve what feature or effect? Why? Yeah. AUDIENCE: Redirections. DAVID MALAN: Redirections. So this is kind of a low-level way of describing it. But 301, even though it says moved permanently, that's a more technical hint to the browser saying, Harvard moved not to whatever URL you just came from, but to this URL specifically.
And now Harvard was probably, if you recall, redirecting me from what URL? If I wasn't already at that URL, where might I have been? Maybe dot com, if they actually own multiple domains and were redirecting. That could work. What else? Yeah. AUDIENCE: Just HTTP. DAVID MALAN: Yeah. Maybe I just typed in HTTP, and Harvard, in the interest of security, wants to force my browser to request this page again via HTTPS. Sometimes a website might prepend the www if you haven't typed it in, or you can be redirected most anywhere.
In fact, if you go to CS50's own website by just typing CS50.harvard.edu, watch the URL. You'll be redirected to a more specific page, depending on the time of year. So we use these tricks, as well. 404 not found might look like this, but inside deeper of that metaphorical envelope is the actual contents of the web page. So you get back not only these HTTP headers, as they're called, in the top of the response, so to speak, but you also get back HTML, yet another language we looked at, this one actually a language, but not a programming language.
These tags tell the browser exactly what to do and to render. We introduced this style tag, though. What did that allow us to do that HTML alone did not? Yeah. Use CSS to beautify the site and just make it nicer. HTML, for the most part, is about structure and about tagging the contents of your web page in a way that the browser finds helpful. But CSS is really for the user's benefit, at the end of the day, and his or her eyes, because it really lets you control font size and positioning and lower-level stuff that you might have started tinkering with with the most recent problem set.
Now, we'd proposed that you probably shouldn't just start typing CSS inside of your HTML page because it's just a little harder to maintain as your examples get more sophisticated. So you might factor it out. And odds are you did this for the problem set because when making a home page, if you have the same CSS styles across multiple files, it would be pretty silly and inefficient to copy and paste them again and again when you can factor them out like this. Lastly, we looked at JavaScript, last time, another programming language that's super similar to see, at least at first glance.
But it actually gets rid of a lot of the lower level headaches like pointers and memory addresses and that that we've struggled with in recent weeks. But most important was how we used it. So you can consider a web page like this as once it's loaded by your browser as just being a tree structure. Thinking back a couple of weeks to our discussion of data structures and each of these nodes in the tree we saw in JavaScript can be manipulated. And via that very simple principle, writing code that modifies this existing tree in the browser's memory, means you can make much more dynamic things like Gmail and Facebook and any number of websites that are constantly changing.
You did not do this yet for the problems set. You made static web pages just by hard coding HTML and CSS. But starting next week, once we have, thanks to this week, the vocabulary of Python will you start to make things more dynamic and then even bring back into play JavaScript, bringing all of these various threads together. And to include the JavaScript, recall, we used either a script tag at the top or refactored it out to a file. Or in some cases, it's necessary or beneficial to move it down to the bottom of the file or factor it out like that, but more on that down the road.
So any questions on last week or on HTTP, HTML, CSS, or TCP/IP? No? Anything at all? Oh, yeah? AUDIENCE: So in what case would you put the script tag up at the top [INAUDIBLE] DAVID MALAN: Good question. So in what cases would you put the script tag up at the top versus at the bottom? If the code you're writing in JavaScript manipulates the DOM, the tree that I had on the screen just a moment ago, the catch is that that tree needs to exist when your code is executed. So if you, for instance, have JavaScript code up here in the head of your page, but the nodes in the tree, the tags that you want to manipulate in changing things to red to green to blue like we did last week,
or making things blank, are down here in the page, you can't write your code up here and have it change things in the page down here because it's happening out of order. So similar in spirit to C where things have to happen in the right order, if you want to change something down here, your code needs to at least be down here, or you need to use some fancier techniques to say, I'm going to write my code up here but wait a few seconds before executing it until the whole webpage is loaded. So for most of the examples we looked at, this was not an issue.
But we'll come back to this perhaps before long. All right, so let's now take the same approach that we did last time of introducing one language by way of another. You'll recall, of course, that we started the whole semester with Scratch and then we transitioned a few weeks back now to C. Last week we made some comparisons with JavaScript. Let's do the same thing briefly with Python but then spend more time at the keyboard comparing the two to see what actually is different about these. So why in another language, though, first?
We have Scratch, C, JavaScript, Python, not to mention HTML and CSS for different purposes. Like, why do we have all of these darn languages already? Why didn't humans just decide, that's it, we're all using Scratch? We're all using C or JavaScript or Python? What's, perhaps, the intuition behind that? Why are there so many damn languages, not to mention in this one course? Yeah? AUDIENCE: [INAUDIBLE] DAVID MALAN: Say once more? AUDIENCE: Different ones are good for different things. DAVID MALAN: Yeah, different ones are good for different things.
And this probably goes without saying for something like Scratch, right? It's so visual. It's so graphical and animated. It makes sense that the puzzle pieces-- or that the language itself is based on puzzle pieces and dragging and dropping. So maybe languages are tailored to certain applications. But is that true for C, Python, and JavaScript, which are all text-based languages we'll see? AUDIENCE: [INAUDIBLE] for example, they're different levels of abstraction. DAVID MALAN: OK. Different levels of abstraction. AUDIENCE: C is very [INAUDIBLE] actually dealing with a lot of things that you don't have to think about in Python-- DAVID MALAN: Good.
AUDIENCE: --where these sort of things are taken care of for you, such as memory allocations and so on. And so depending on what level of abstraction you want to work on and what parts you want to manipulate. DAVID MALAN: OK, good. Bringing it back to abstraction does make sense. C is, indeed, very low level, literally having the ability to manipulate memory and via pointers and so forth. And that's great because you can do anything you want with the computer. But it comes at great risk and great cost. One, the cost is human time.
It's just painful to write that kind of code sometimes. Two, it's also very risky because if you make a mistake, even a simple mistake, the whole computer can crash. And we didn't see examples of this, but you can make your code vulnerable to a hacker if he or she is able to somehow exploit a memory-related bug and read all of the passwords in your program, or something like that. So with great power comes great responsibility is kind of the mantra of C down here. But JavaScript we saw allows us to do things a little more high-level.
There were no pointers. There was no memory. We didn't talk about things at that level. We talked about things at the level of a tree, a DOM in memory and changing colors and positioning of things on the screen. And that's, indeed, a higher level. Now, Python is not necessarily even web-centric. It's more of a multi-purpose language. People use Python to write command-line programs, like we will soon, at the keyboard, like we've been doing with C. You can also, though, use it, as we'll see next week, to generate other languages.
So next week we will write code in Python, the language we're about to see, to generate another language, HTML and CSS. Some of you probably noticed in your homepages that you had some redundancy. You probably had similar tags or similar structure, maybe a similar menu across pages. Python and other languages will let us factor that out and generate those commonalities a lot more easily, among many other things. And it's also arguably easier and faster to write because it comes with so many more features, as we will soon see.
So in fact-- you know what? Let me do this. Let me go ahead and open up CS50 IDE. Let me go ahead and create a new file. And out of curiosity, of our recent problem sets, what was maybe among the most challenging programs you've written? AUDIENCE: Crack. DAVID MALAN: OK, crack was a good one. What else? AUDIENCE: Resize. DAVID MALAN: Resize, recover. Yeah, definitely the forensics ones. And more people probably did recover and resize. So let's take resize, for example. So let me go ahead and write a program in a file called resize.py for Python, instead of .c, and see if we can't spend, what, few hours, couple days, as you probably did in C, implementing resize.
Well, let me go ahead and do this. I'm going to go ahead and-- let's see. First I'm going to import some features that just come with Python. And I'm going to go ahead and say from sys import argv. And I'm going to go ahead and also do from pil import image. Don't know yet what these are. We'll tease this apart in a moment. But then let me just do a check. If the length of-- rather, if the length of argv does not equal 4, I'm going to go ahead and exit for the user and say the usage of this program is Python resize.py and in file, out file.
So even though some of this should look cryptic at the moment, there's some commonalities-- argv, you recall, from C, and this usage string that we printed out whenever anything went wrong. That looks very similar in spirit to C. And what did we do in resize? If you implemented resize, like the less comfy version, to increase the size of things, you probably declared a variable like an and got sys-- or rather, argv bracket one to get access to it. I'm going to go ahead and convert that or cast that to an int. You probably had an infile variable that gave you access to argv two.
You probably had an out file variable that gave you access to argv three, and so forth. And it turns out in Python, you know what? I can actually use a library, code that other people have written. Let me come up with a variable called in image, like infile. This is my input image. And that's going to equal image.open because I want to open this thing called infile. And then the width-- let me get the width and the height of the existing image by doing input image.size. And then let me go ahead and make a new image-- out image, I'll call it-- which is going to equal the input image calling a resize function and doing the width times n, which is the number the human probably
typed in, and height times n, which is the number the human typed in. Then let me go ahead and just save the outfile as follows. Outfile, OK. Done. Problem set three. Tada. OK, either really exciting or really, really disheartening perhaps. So with the right language, as you say, can you solve problems so much more easily. Now, I'm being a little disingenuous because I'm also leveraging what's called a library. And we had access to these in C. And undoubtedly we could have dug a little deeper on the internet into other people's available code and found maybe a library for bitmap files.
But notice that there is no dealing with padding now. There's no dealing with arrays. There's no dealing with memory because I'm using the right tool for the job. And if I wrote this code correctly-- and let me cross my fingers that I didn't make any typos. Let me go ahead here and get myself a copy of smiley, which I brought with me. So that was the tiny little image from last week. Let me go ahead and open this in the IDE. Smiley, super small. Just a few pixels there. And let me go ahead now and run Python, which we'll see why in a moment, resize.
Let's increase this by a factor of 10, increasing Smiley, and call it out.bmp. Now let me go ahead and open out.bnp and voila, it indeed seems to work. Right, no funky colors. No weird sizes. No padding. No padding of all things. It's just now Python. So you can probably glean some of the logic that's going on here. But some of it certainly should and probably does look magical. So let's use today to tease this apart and appreciate not only what you can do with another language like Python, but how it's similar and different and how it actually is built upon something like C.
So let's do some comparisons first so that we can see that it's not a huge stretch to introduce yet another language so quickly. So recall that in Scratch if we wanted to set a variable, like counter, to zero, you might simply do something like this, setting it equal to zero at left. In C, we would do the same thing here at the right. In JavaScript, this instead looked a little different. What did we do in JavaScript? Yeah, we used let instead because we don't specify explicitly the type. But we do need to tell the computer, let me have this variable called counter.
In Python, it's going to be that. So we've gotten rid of the type still. We've gotten rid of any mention of let or another keyword. And we've gotten rid of-- perhaps most gratifyingly-- semi-colons are gone. No more semi-colons. And no more curly braces in the way you've seen them thus far. So that was C, JavaScript, and now Python. So how about something like this? In Scratch, if you wanted to increment a counter by one, you would use a block like this. In C, we would do the same on the right here in code. In JavaScript, did it look any different on the right?
No. You haven't had occasion to use this yet. But one of the sort of revelations of JavaScript was that's also JavaScript. It was identical. Something like this, though, is Python. So it's almost the same. But I've gotten rid of the semi-colon. But the logic is exactly the same-- set counter on the left equal to whatever it is on the right plus one additional value. What about this? This in C had what effect? Incrementing the variable. So this is exactly the same. It's sort of a nice shorthand notation for doing counter equals counter plus 1, which just gets a little tedious to type.
We had that same syntax in JavaScript. And you can probably guess in Python, what's it going to look like? AUDIENCE: Same thing without the-- DAVID MALAN: Same thing minus the semi-colon. So pretty nice pattern so far. Languages just keep getting trimmer and trimmer, if you will. In C, recall that we could just do plus plus, which was another trick for automating that same process. JavaScript allows for the same. And if you really like this syntax, I can't show you a slide for Python. Doesn't exist. Can no longer do plus plus.
So we're paying a price. The author of Python did not include this in the language. But that's OK. We at least have this one, which is not too horrible. So what else did we look at last time? An if condition like this, comparing if x is less than y, in C it looks like this. In JavaScript it looks like this same thing. In Python, it looks like this. So gone are the curly braces. Added is a colon. And what you don't see yet is that indentation is going to be important. So any of you have been a little fast and loose with style 50 and, like we've seen at office hours, all of your code, however many lines you've written for whatever reason is all aligned on the left and nothing
is actually indented. Now Python is not going to tolerate that. Python requires indentation for logic. And so this is actually a stylistic feature of the language. It forces you to adopt good visual stylistic habits because the code just won't run if you haven't indented it properly. So anything that's going to happen if x is less than y needs to be indented, say, four spaces underneath that colon. What else have we seen? In C or in Scratch we had this block for if's and elses. In C it looks like this. In JavaScript it looks like this.
In Python it's going to look like this, albeit with indentation below each of those colons. How about this? When we had three-way a fork in the road-- if else, if else-- in C it looks like this. JavaScript looked the same. In Python, looks a little funky. It's going to look like this-- elif but three colons, this time two. What else? We also looked at forever loops in Scratch, in C, and in JavaScript. You could use exactly the same syntax in Python, almost the same. Gone are the curly braces, added is the colon. And the slight subtlety, if you noticed, true and false are now proper nouns, if you will.
Capital T capital F is necessary to write. How about a for loop? So in Scratch, we could very easily say, repeat this 50 times. C and JavaScript is a little pedantic in that you have to initialize and increment and check. Both C and JavaScript take that same approach, although in JavaScript we of course use let instead of int. Python is a little more succinct although a little less explicit step by step. You just do this. For i in range of 50 is the way of saying start iterating at 0, count all the way up to but not including 50, thereby giving you a range of values.
So this is the one that's perhaps the most weird thus far, but still a little more succinct to write. So in C, we had so many data types-- bool, char, double, float, int, long, string-- the last of which, of course, came from the CS50 library. And there's others that you can use in C, as you might recall, from problem set 3, perhaps. In Python, we're going to shorten this list, at least initially, to just these data types. In Python, we're going to have bools for true-false, floats for real numbers, ints for integers, and then strs for strings.
Just a little more succinct, but it does actually exist. str in Python is a real thing. It is not a CS50 addition. There are other data types that come with Python. In fact, this is where the language gets powerful. And those of you who came from a Java background or C++, the subset of you who have programmed before, you have more features in Python just like you do in those other languages that we did not have in C. In Python, you have dictionaries or hash tables. You have lists, which are arrays, but that can automatically resize.
You don't have to decide in advance how big or small they are. Range we just saw, it's a range of values, like 50 of them, set in the mathematical sense. It's a collection of things that ensures you don't have duplicates in that collection. And then tuple is a combination of things kind of like for math when you have x comma y or latitude comma longitude. Any time 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 getFloat, getInt, and getString, which behave exactly
like their C 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 wanted 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 is 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 who have seen Python before, there's other ways to do this. There are several approaches. This is, perhaps, the most comparable for our purposes today. What else are you're going to 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'd figure out the command for you in the IDE or the sandbox or lab. In Python, you're going to skip the compilation step. When you want to run a program in Python, you're going to 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 middle man 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, an interpreter. And that interpreter's purpose in 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 bytecode. And bytecode 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 that didn't 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 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.py. 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.c? There is no main function necessary here. What else is missing? AUDIENCE: Printf. DAVID MALAN: There is no mention of printf. It's instead print, which is a little more human friendly. AUDIENCE: Libraries. DAVID MALAN: There is no mention of header files or libraries at the top of the file.
I just dived right in and got to it. Yeah? AUDIENCE: No semi-colons. DAVID MALAN: No semi-colons. What else? What else? Yeah? AUDIENCE: No backslash n. DAVID MALAN: No backslash n. I probably-- I 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? AUDIENCE: There's no f in printf. DAVID MALAN: There's no f in printf, yep. Something else? 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 int. There's no mention of void. I mean, my God. Why didn't we just do this last time? And so this is why languages evolve. People realized years ago, gee, C is serving us well. Once I understand pointers and the syntax, OK, I got it. But my God, it's just so tedious to write even the simplest of programs because I have to do hash includes, standard io.h, 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 hello world.
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? In C, recall, I would have done dot slash hello.py. 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 friend that just has to convert hello.py 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. You know, the price we're going to 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 tradeoff. 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 Python. Let me go ahead and call this string zero.py because I'm dealing with strings. And let me go ahead and do s to give me a variable. Get string. Let me prompt the human for his or her name like this and then let me go ahead and say hello.
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 percent s. I don't need to put a second-- or, I do need to put a second comma here. But I can just do this, which is a little simpler. And this is not correct. I'm not practicing what I preached. Get rid of the f. Just print what you want to print, indeed. So s, notice, is apparently a variable because I'm assigning it a value from right to left. But notice that I'm not specifying the type.
So Python does have type. str we said is the string equivalent. But you don't have to mention it. Python, like JavaScript, will just figure it out, even without a keyword like let. But I do need to add one thing. What's that? AUDIENCE: You need to import the getString? DAVID MALAN: Yeah, getString is a CS50 thing. And we're only going to use it for a week, but I do need to import it. And the syntax with which to do this is to say, from the CS50 library, import a function called get string. I don't need to import any more with commas.
That one suffices for this program. Yeah. AUDIENCE: Would you want to-- instead of saying hello your name, would you want to first getName that says [INAUDIBLE]? You're not indicating where the error is [INAUDIBLE].. DAVID MALAN: Sure, let me come back to this in one second. Let's run this program first to demonstrate that it indeed does what we saw it do last week. And let me go ahead here and do this time Python of string 0. Let me go ahead and it's just waiting for my name. So I'll type in David. Hello, David. But as you propose, what if you wanted to flip this around?
Well, suppose I wanted to say the person's name and then something like hello because I'm just excited to see them, instead. Let's see what this does. Let me go ahead now and run Python of string 0. Type in my name. And it's almost what I think you intended. But there is a bug-- an aesthetic bug, at least. So it seems with Python's print function you don't need to use the placeholder like percent s. But it would seem to presumptuously add a space for you after everything you're passing in as an input to print itself.
So notice print is taking how many arguments according to this highlighted portion? How many arguments might you infer? AUDIENCE: S space and then the thing. DAVID MALAN: Two? Yeah, so two. One is s, comma, and then the rest is what's highlighted in green here. Yes, there's a second comma there, but it's inside of the string. So just like in C, that's sort of a red herring. There's only two arguments here. But it seems that the print function-- and you would know this by reading that documentation-- if you pass in two or three or more arguments, it prints all of them.
But separates them with a single space. So this isn't quite right. So this is actually a great motivation for cleaning this up. If I want to actually improve this program and tidy it up a little bit, let me do that in version one here. Let me create another file called, say, string1.py. Let me start where we started a moment ago. And let me actually use a placeholder akin to C. So if I want to do, for instance, hello so-and-so, it turns out you can actually say, hey Python, put a variable called s right here. However, if I run this as is, there's still going to be a bug.
It's not quite solved yet. But when I hit Enter now and type in my name-- all right, this is obviously stupid looking. So it seems that I need to tell Python that this string that I'm passing in, hello comma so and so, is a formatted string. It's a placeholder string that it should make some changes to. And this is a little weird, cryptic syntactically in Python. But the way you do this in Python is you put an f before the string itself. So I'm sorry, we got rid of the f a moment ago. So we just called it print. Now we're reusing a different f here.
And it's stupid-looking syntax, admittedly. But this just means hey, Python, the following double quotes or single quotes that you're about to see should be formatted by you in a special way. And it literally goes at the beginning of the string even though that does admittedly look weird. But if I now rerun this Python string one and type in my name now, now it does the substitution. So I can flip it around logically much more flexibly now and do something like hello because now I'm passing in one argument that print will format for me.
So when I type in my name now, I'm not going to get that superfluous space. And now I have complete control over the formatting of the string. So you know, sort of two steps forward, one step back, perhaps, syntactically. But it does allow us to do what we want this to do. We could write the same program using ints and floats using getInt and getFloat. Would look exactly the same. You don't need to worry about percent s versus percent i versus percent f. You just type in the variable name inside of those curly braces.
All right, let me go ahead and do some quick math. Let me go ahead and do this. Let me go ahead and create a new file. We'll call this ints.py for integers. And let me go ahead and get this access to-- how about the CS50 library's get int method or function which exists. Then let me go ahead and declare a variable called x and get an int from the user and just prompt him or her for x. Then let me go ahead and do the same thing and just get y from them, as well. And then down here, let me just do some simple math. And we did this way back in week one by printing as follows.
Let me go ahead and just print out x plus y equals-- and this is what's cool now about this curly brace feature. You can actually do not just variable's 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 going to 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 equals whatever the actual sum is.
AUDIENCE: Just following up, what does f mean? DAVID MALAN: Format. Format the following string for me. Good question. Let's do just a few copy/paste but change the operator here. So x minus y, I want to see what this looks like. X, say-- what did we do last time? Multiplying by y. I want to do that math, too. I can divide as well. And then we had one more, which was modulo, or modular arithmetic, which, recall, was the percent sign. 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 ints.py. And let me go ahead and do one and say two. 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. Say again? AUDIENCE: You're getting a float. DAVID MALAN: Yeah, I'm getting a float. Like, Python itself seems to have fixed a bug in C itself. What happened in C when you divided 1, an 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 the C would truncate everything after the decimal point. And yet, Python seems to have fixed this problem. And this is actually a somewhat recent phenomenon. And this 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, true division, where if you divide two ints 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, all right, 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 of these two steps forward, one step back. But it's there, so problems can still be solved in the same way. And this, if I save it and rerun that same code, 1 and 2, now I get back 0, 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.py. And let me do the same thing, from CS50 import getFloat 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. Let's 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 of floats.py. 1 divided by 10 this time. And I get-- dammit, bug. How do I fix this? All right, so just a simple f. Make it a format string. No big deal. So let's rerun this, 1, 10. OK, hoo, hoo. That's a new one. What is going on there? AUDIENCE: [INAUDIBLE] DAVID MALAN: I did define z in the line above it, and what was your comment? AUDIENCE: You used x plus y. DAVID MALAN: I did use x plus y, but I think I-- oh, wait, OK. I'm sorry. Let's-- OK, so we can fix that.
Let's-- sorry. There. OK, so 110. Hmm, still wrong. Good catch, thank you, though. Why is 1 plus 2 11-- or 1 plus 10, 11? Yeah? AUDIENCE: [INAUDIBLE]. DAVID MALAN: Wait, wait, wait. Sorry. AUDIENCE: [INAUDIBLE] [LAUGHTER] DAVID MALAN: This brings me back to my earlier point as to how tired I am. So this is correct. So Python does math correctly. But-- OK, 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 I if I do 1 divided by 10, OK, 1 divided by 10, as expected, does actually work here.
So 0.1, that's correct. But remember in C-- let me dig myself out of this hole-- remember in C 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 to, 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 2f.
So this is saying, hey, Python, format the variable that's to the left of the colon using two decimal points. And by the way, it's a floating point value. So this f has a different meaning. This is f as in float. The f to the left is in format. So let me go ahead and run this. 1 divided by 10. And OK, still looking pretty good. Let's do maybe three decimal places, save that, rerun it. 1 divided by 10. Still pretty good. Let's get a little ambitious. Let's do it 50 decimal places out, 1 divided by 10, and damn it. Python has not fixed this fundamental problem.
So we describe this problem as what? What's the sort of buzzword here to sort of explain or forgive this issue? AUDIENCE: [INAUDIBLE] DAVID MALAN: 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? AUDIENCE: [INAUDIBLE] DAVID MALAN: 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 PC or 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 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 of those problems. But frankly, in the world of data science and analytics, it's certainly important precise mathematics.
So there are solutions to this problem. But it requires special libraries, typically, 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.c. And notice that this code in C from a few weeks back just multiplied i by 2, by 2, by 2. So it was doing exponentiation, so to speak-- 1 to 2 to 4 to 8, 16, 32, 64, and so forth.
What happened if we waited long enough and watched this program a few weeks back? AUDIENCE: You go to 5 billion instead of-- DAVID MALAN: Yeah, we hit roughly 5 billion or 4 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 1, 2, 4, 8, 16, 32, 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 going to overflow once we hit roughly 2 billion. Why? Why two billion, give or take? Why that value in C? Yeah? AUDIENCE: [INAUDIBLE] DAVID MALAN: 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 four 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 one billion, we overflow. So 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.py, which is a program I wrote in advance. It's on the course's website, as always, if you want to take a look more closely. And if I go into this file in weeks one, overflow.py, 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 import sleep. 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 six directory, weeks one, and run Python of overflow.py, 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.
Whew, look at it go. Only up there. Look up there. What's it doing differently? It's counting a lot higher than 2 billion. So what might you infer about integers in Python? AUDIENCE: [INAUDIBLE] DAVID MALAN: Say again? AUDIENCE: An integer is defined to be quite a number of bits. DAVID MALAN: OK, an integer is defined to be quite a number of bits. And indeed, that's the case. 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 data types. We could have done this in C. We could have used longs, for instance. But notice that with Python you just get 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 one and look at a few from week two and three and really take a look not just at 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.py, reminiscent of conditions.c some time ago. Let me go ahead and import from CS50 getInt this time and get myself another x with getInt x from the user. Then let me go ahead and ask them for getInt y from the user. And then let me go ahead and just compare them. And so per our comparison with 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.
Elif 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 like in C, 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 four spaces and three. You've got to have, for instance, four all the way. Notice that I've got the colons consistently there. But notice that I don't need the parentheses, either, anymore.