CIS551 Course-Transcript
CIS551 Course-Transcript
Python Fundamentals
What you'll do
Course Description
The systematic approach you will follow uses repetition and practice to
reinforce the core concepts of Python. By building a solid understanding
of Python, you will gain the ability to program in the real world.
Walker M. White
Senior Lecturer and Stephen H. Weiss
Provost's Teaching Fellow
Cornell Computing and Information Science,
Cornell University
Walker White is also the Director of the Game Design Initiative at Cornell.
In this role, he directs the computer game minor at Cornell and teaches
the primary game design courses. He is a strong proponent of project-
based education, incorporating interdisciplinary teams, and he is the
faculty sponsor of the CU-AppDev engineering project team.
Table of Contents
Module 1: Working with Python Environments
© 2019 eCornell. All rights reserved. All other copyrights, trademarks, trade names, and logos are the sole property of their respective owners.
Python Fundamentals
Cornell Computing and Information Science
© 2019 eCornell. All rights reserved. All other copyrights, trademarks, trade names, and logos are the sole property of their respective owners.
Python Fundamentals
Cornell Computing and Information Science
© 2019 eCornell. All rights reserved. All other copyrights, trademarks, trade names, and logos are the sole property of their respective owners.
Python Fundamentals
Cornell Computing and Information Science
© 2019 eCornell. All rights reserved. All other copyrights, trademarks, trade names, and logos are the sole property of their respective owners.
Python Fundamentals
Cornell Computing and Information Science
© 2019 eCornell. All rights reserved. All other copyrights, trademarks, trade names, and logos are the sole property of their respective owners.
Python Fundamentals
Cornell Computing and Information Science
Video Transcript
The purpose of this video is to introduce you to Codio. What is Codio,
you might ask? Codio is a virtual machine. It's essentially a separate
computer that's running off in the Cloud. This particular computer is
running a version of Linux. It's running a version of Ubuntu if you know
anything about Linux, but that's not really important. What is important is
that it is a computer that you can access from your browser. You will
notice that there's a link to Codio on the Canvas page, and when you
click on it, you'll see much the same as what I have on the screen before
me. You'll see several drop-down menus that you can choose, you'll see
some demo instructions in the center of the screen, but more importantly
you'll see this initial Sandbox off to the left. This has all of the basic
features of your computer. You can save and open files, you can
organize the files into folders, you can run programs, and those programs
can be yours or those that are written by someone else. Now, the
software is very limited, but it's more than enough for what we need for
this course. Most importantly, Codio is used in the final project.
Throughout this course, you're going to be working on a simple but
complete program, and you're going to be using Codio to write and test
the project. You're also going to be using Codio to submit the project for
assessment at the end. But that's not the only reason we want to have
Codio. It's also very useful for just playing around and experimenting.
You'll notice that the link for the module is titled "Sandbox"; that's just
© 2019 eCornell. All rights reserved. All other copyrights, trademarks, trade names, and logos are the sole property of their respective owners.
Python Fundamentals
Cornell Computing and Information Science
because we just want you to experiment. This is to give you very easy
access to Python without having to install it on your own computer.
Now, some of you might already have Python installed in your computer,
and you might wonder why do you need to use Codio? The nice thing
about Codio is that it's a uniform programming environment. Everyone
who uses Codio is going to have exactly the same installation; that
means it's going to be much easier to match your work to what you see in
these videos. It also limits the necessity for tech support. We can
guarantee that you have exactly the right Python, we can guarantee that
you have exactly the right add-ons, and we can access your files without
having to go onto your own computer, and that way we can help you
more. Now, with that said, we need to be careful. One of the philosophies
of this course is that we want to be able to teach you how to program in
the real world. And if you just work with Codio, that's not necessarily
going to help you. First of all, Codio is going to disappear at the end of
the course. But more importantly, there are lots of real-world tools that
you need to know how to use. So we promise that in addition to Codio,
we will make sure that you are prepared. We will show you how to use
everything on your computer to do exactly the same things that you can
do on Codio. We're going to give equal time for Windows and Mac OS —
or Linux, if you're using that — and we will periodically spot-check your
work on your computer. Finally, before the course is over, we're going to
verify that the final project is not just running on Codio but is working on
your own computer; that way your work is not going to be lost when we're
done.
Video Transcript
In this video, we're going to talk about how to work with files in Codio.
Working with files is one of the most basic features of your computer. On
your computer, you'll often have nice graphical tools for opening and
manipulating files. Here on my computer, you'll notice that I have a folder
on my desktop for this course. If I click on the folder, it shows me its
contents. Inside of this folder is a file, which I can double-click on and
open. In addition, there are other folders inside of here, and if I double-
© 2019 eCornell. All rights reserved. All other copyrights, trademarks, trade names, and logos are the sole property of their respective owners.
Python Fundamentals
Cornell Computing and Information Science
click on them, I will go deeper into the folders. All of these features are
provided by Codio by what is called the Filetree. You will notice this thing
on the left that has the name Filetree, and then down underneath are the
contents of Codio. You'll notice that I have three folders — folder1, 2, and
3 — as well as a file called ".settings". If you want to open up a file, you
just double-click on it. We're going to double-click on the file .settings
here. Now this is going to have a lot of information in here that we don't
really understand yet, but as you can see, it's a file that we can look at.
We can also close this file by going to the tab and selecting the Close
button. As we mentioned, folder1, folder2, and folder3 are all folders. If
you want to open a folder, just click on the arrow key that's to the left of it;
that will expand the folder and we can now see the contents. Once again,
I can now double-click on a file and open it. In addition to working with
the files that are already on Codio, you can also transfer files from your
computer and download them from Codio. To transfer a file to Codio, we
just select a folder that we want to put it in, choose our right-click, and
this will produce a menu. And now we will select Upload. This provides a
nice box for us to upload to. We're now going to take a file from our
computer, drag it onto here. It has now finished the upload; we can close.
When we look at the folder, we can now see that that file has been
uploaded from Codio. If we want to download a file from Codio, we just
select the file, we right-click it once again, there is an option to download.
And now this download's using our normal browser. You'll notice that
there's an interesting error message here down at the bottom saying that
"This type of file can harm your computer." That's because I've
downloaded a Python program, and obviously a browser doesn't like it
when you've potentially downloaded malicious programs from the web.
However, this is my own program, so I know that this can't be malicious,
so I've decided to keep it.
Video Transcript
Now, when you start the Terminal, you're actually inside of a folder. Just
like when you're on your computer and you double-click on a folder to
see its contents, I can see the contents of this particular folder. To do
that, I type the command "ls" and hit Return. "ls" stands for "list files."
You'll notice that I see the files folder1, folder2, and folder3. So, as you
can see now, when I start the Terminal, I'm actually in the same location
as the Filetree to my left, where you can see folder1, folder2, and folder3.
However, I seem to be missing a file. You'll notice in the Filetree there is
this file called ".settings", but I can't actually see that in the Terminal.
That's because files that start with a period are hidden. If I want to see
those, I have to type a different command. I have to type "ls", space, and
then a minus or dash, immediately followed by "a". When I type this, now
I can see all of the files in this folder, including those that are hidden. You
can see the .settings at the end. You can also see some other mysterious
files here, like .guides and .codio. These are not important. They contain
some of the tools that will help us work throughout this course. You can
look at them if you want to, but we recommend that you don't change
them, because it'll just make life difficult for you if you do.
© 2019 eCornell. All rights reserved. All other copyrights, trademarks, trade names, and logos are the sole property of their respective owners.
Python Fundamentals
Cornell Computing and Information Science
In addition, I can now type "pwd" inside of the Terminal to see what my
Active Directory is, and you'll notice that I am now located in folder1,
which is located inside of workspace, which is located inside of codio,
which is itself located inside of home. Another interesting thing is that you
can see that there's more information before the white box, which is what
we call the prompt. You can see that it actually says "workspace/folder1."
So I can always quickly tell what folder I am in just by looking at the
prompt. The information to the left, the thing that says, in my case,
"codio@prepare-grille," this is information about your Codio machine.
You will see something slightly different here, because each one of you is
working on a different Codio machine. Now, I'm located in folder1, and I'd
like to go back to the workspace. How do I go back? Well, the way I
would do that is once again I would use the "cd" command, but now I
need some way to go back to the workspace folder. You might think that I
would do that by typing "cd workspace". Unfortunately, I get an error
message in this case. That's because "cd" will only allow you to change
the directory if that directory is currently inside your folder. There is no
workspace inside of folder1; workspace is the parent of folder1. To go
backwards, instead, I have to type ".." Now, I can see that, once again,
I'm in the Active Directory, with folder1, folder2, and folder3. And using
this technique, I can even back out of the Filetree. Now, I'm in the codio
folder, which you can see only has one thing inside of it, which is the
workspace folder. All of these commands that I've shown you — "ls",
© 2019 eCornell. All rights reserved. All other copyrights, trademarks, trade names, and logos are the sole property of their respective owners.
Python Fundamentals
Cornell Computing and Information Science
"cd", "pwd" — are Unix commands, right, because of course, we're typing
all of these commands into a Unix virtual machine. But they also exist on
any operating system, and that's the reason why we're the most focused
on them. Both Windows and Mac have equivalent commands in their
Terminal. They're also the only three commands that we need for this
course. Of course, there are a lot of other Unix commands that you might
be interested in, but this is not a course in how to use Unix. If you're
interested in learning more about Unix, this module does have a link to
more resources to help teach yourself on your own. And there you might
also learn a little bit more about how folders and files work on Unix as
well. But as I said, we won't need anything more than what we've shown
you in this video in this course.
© 2019 eCornell. All rights reserved. All other copyrights, trademarks, trade names, and logos are the sole property of their respective owners.
Python Fundamentals
Cornell Computing and Information Science
If the Terminal becomes unresponsive at any point, you can open a new
Terminal session via Tools --> Terminal.
© 2019 eCornell. All rights reserved. All other copyrights, trademarks, trade names, and logos are the sole property of their respective owners.
Python Fundamentals
Cornell Computing and Information Science
© 2019 eCornell. All rights reserved. All other copyrights, trademarks, trade names, and logos are the sole property of their respective owners.
Python Fundamentals
Cornell Computing and Information Science
In this first video, Professor White describes the tool that Windows offers
for Python programming and how you can use it to work with files on your
machine.
Video Transcript
You've already learned how to use the Terminal in Codio and how to
work with Python in that environment. But as we've said, you should
always learn how to use these tools on your own computer. First of all,
Codio is going to go away at the end of the course and you won't have
access to it anymore. But more importantly, we really do feel strongly that
you should learn to work with real-world tools. Now with that said, you
should always use what you find to be easiest while you're learning. If
you like learning in the Codio environment, that's great, but we want to
give you the chance to work on your own computer as well. In this video,
we're going to show you how to use the Terminal — or things like the
Terminal — in Windows. Windows isn't Unix so these things aren't going
to be exactly the same. And that's one of the reasons why Windows is
not the preferred environment for developing Python. Now, I like
programming in Windows and I have a Windows computer that I use for
my game design classes. But for Python, I much prefer to use a Unix
system. With that said, Windows works well enough, and then if that's
what you have on hand, you can certainly follow along.
© 2019 eCornell. All rights reserved. All other copyrights, trademarks, trade names, and logos are the sole property of their respective owners.
Python Fundamentals
Cornell Computing and Information Science
down at the bottom. We're going to start the PowerShell and it's going to
pop up as a separate window, and you'll notice that this looks a lot like a
Terminal. It doesn't have the white box but it does have a flashing cursor,
and it has a prompt off to the left, and I can type text commands into this,
much like the Terminal; text commands that I'm familiar with, like "ls" to
list the files. Now, you'll notice that this is not exactly the same as it is on
Unix; on Unix when I type "ls", it'll just list out the names of the files often
horizontally. On the PowerShell when I type "ls", the names of the files
are listed in the right-hand column and it has additional information to the
left such as when the file was last modified. As with the Terminal, when I
started this window it was in an Active Directory, and you might wonder
where is this Active Directory? This is what is known as your Home
Directory. To find this in Windows, click on "This PC" and go up. In this
case, we see a folder with my name on it. You'll see a folder with your
account name on it as well. If you double-click on this, we are now in the
Home Directory, and you will notice that the folders and files in this
directory are the same as they are in the Terminal. If I click on a folder,
it'll give me information about when that was last modified, and that will
indeed match up with what it is that I see in the Terminal. "ls" isn't the
only command that is supported by the PowerShell; the other commands
that you're familiar with, like "cd" and "pwd", are also supported in
PowerShell. If I type "pwd", I can find out what my working directory is. In
this case, I'm inside of the folder Walker, which is inside of the folder
Users. It's a lot like what I see on a Unix system. One of the main
differences actually is that the slashes go in the opposite direction than
they do on Unix. Now, in this case, I want to go inside of the folder
CIS551, which is located on my desktop. That has several files for this
module and for Module 5 in this course. It also has the hello.py file, which
I showed off in the Codio demonstration. To go there, we just use the
"cd" command. In this case, I'm going to type "cd" to desktop. Type "ls"; I
will notice that the CIS551 folder is now in my Active Directory. If I type
"cd CIS551" again, I am now inside of that directory, and now I can
proceed as normal.
In this video, Professor White shares several tips that will enable you to
work more quickly and efficiently in the PowerShell.
Video Transcript
© 2019 eCornell. All rights reserved. All other copyrights, trademarks, trade names, and logos are the sole property of their respective owners.
Python Fundamentals
Cornell Computing and Information Science
Now that you know how to use the PowerShell on Windows, there's
some nice tricks that we'd like to show you in working with it. Now, these
tricks aren't really necessary; you can work your way through the course
without knowing any of them. But you'll find that they make some tasks
faster, or at least less annoying. One of the first tricks that we'd like to
show is tab completion. And this is very useful when you're accessing
files, or for trying to change directories. Right now I have the PowerShell
open to the desktop. If I type "ls", I can see that I have the folder CIS551
open. Now, I want to change into the folder CIS551. So I'm going to type
"cd", space, "c", and instead of typing the rest, I'm going to hit Tab. You'll
notice that it completes to CIS551. It also has some extra slashes around
what I've typed, but that's not really important. If I hit Return, I'm now
inside of the folder CIS551. And if I type "ls", I can now see that inside of
this I have the file hello.py as well as the folders module1 and module5.
I'm going to do this again; I'd like to go inside of the folder module1. I'm
going to type "cd", "m", and I hit Tab. And you'll notice that it completes to
"module1," which is great because that's the folder that I wanted to go to.
Unfortunately, suppose I wanted to go to module5 instead. Well, tab
completion and Windows will always go to the first match, so it's a bit
dangerous to use tab completion when you have things that start with the
same prefix. However, I could solve this if I wanted to go to module5 by
just hitting Backspace and changing the 1 with a 5, and now I'm in the
correct folder. In addition to tab completion, I can also do things with the
up and down arrows. If I type the up arrow, you'll notice that it once again
tries to change the directory into "module5." If I hit the up arrow again, it
gives me the "ls" command. If I give it the down arrow, it goes back to the
"cd" command to change to module5. What's happening here is that the
PowerShell keeps track of all of the commands that I've typed, and then I
can use the up and down arrow keys to navigate through my command
history. And in fact, at any time what I can do is I can hit Return to repeat
that command again. This is very, very useful when you have tasks that
you want to repeat over and over again, which is something that we're
going to be doing later in the course.
Finally, you'll notice that while you're working with the PowerShell, it's
going to be filled with text; possibly the output of programs that you've
run or maybe even error messages if something's gone wrong.
Periodically, to keep yourself from being confused, you'd like to clear the
screen. You can do that by typing the command "clear". And now,
© 2019 eCornell. All rights reserved. All other copyrights, trademarks, trade names, and logos are the sole property of their respective owners.
Python Fundamentals
Cornell Computing and Information Science
everything is erased from the screen and I can start fresh. Finally, there's
one last important trick that we'd like to show. Often when you're working
with Python, you're working with files that are inside of folders, inside of
folders. So on my desktop I have the folder CIS551, inside of that I have
the folder module1, inside of that I have the folder module2, and that has
the file hello that I want to be able to access. Well, in order to access that
file, I'd have to do a lot of "cd" commands, and that can be really
annoying. However, there's a very fast way in order to get to a folder in
the PowerShell. What I need to do is — in order to access folder2, what I
want to do is I want to back up one level in the Windows Explorer. So I'm
not looking at the contents folder2, but I can actually select folder2 itself.
Now what I'm going to do is I'm going to go into the PowerShell and I'm
going to type the command "cd" and space as if I was going to change
the directory. But instead of typing something, I'm now going to drag
folder2 onto the PowerShell. And you'll notice that it has now turned
folder2 into a lot of text. I hit Return, and now you'll discover that I'm in
the right folder.
© 2019 eCornell. All rights reserved. All other copyrights, trademarks, trade names, and logos are the sole property of their respective owners.
Python Fundamentals
Cornell Computing and Information Science
In this first video, Professor White introduces the terminal on the Mac.
While it is very similar to the terminal in Codio, you will see there are
differences in working with files on your machine in comparison to Codio.
Version 10.15 of Mac OS, named Catalina, has been found to affect the
terminal. If your Mac is already running Catalina, please contact your
instructor or the help desk ([email protected]) for assistance.
Video Transcript
You've learned how to use the Terminal on Codio and how to start
Python in the Terminal. But as we've said before, you should really learn
how to use these tools on your own computer. First of all, Codio will go
away at the end of the course, but more importantly, we want you
working with real-world tools. With that said, you should always use what
you find to be easiest when you're learning. If you would rather learn in
Codio, that's fine, but we would like to give you the option to work on your
own computer. In this video, we're going to show off how to use the
Terminal in macOS. The Mac is actually my preferred Python
development environment. That's because it's a Unix environment, and
Python is really designed to be used in Unix. With that said, Linux
systems also work equally as well. However, we're not going to have
separate videos for Linux. That's because a lot of what you can do in
Linux you can also do on the Mac. And honestly, Codio counts as our
Linux examples. Now, the tricky thing about working with the Terminal on
Mac is actually just finding it. We're going to have to find the application
by looking inside of the Applications folder. I'm going to scroll down,
trying to look for the Terminal application, but you'll notice that we don't
actually see anything named "Terminal" or anything that might be the
Terminal. Instead what we do find is a folder called Utilities. This is a
special folder inside of the Applications folder that Apple likes to hide
things that are powerful and they don't want normal users to use.
© 2019 eCornell. All rights reserved. All other copyrights, trademarks, trade names, and logos are the sole property of their respective owners.
Python Fundamentals
Cornell Computing and Information Science
find to be very useful is to have the path option up at the top of my Finder
window, which shows me which folders are located inside of which
folders. This drop-down here is the same thing that I will see when I type
the "pwd" command. Right; when I type "pwd", I notice that I have a
Desktop, which is inside of wmwhite, which is inside of Users; once
again, Desktop inside of wmwhite inside of Users. If you don't have the
path option in your Finder window, you can get this by going to your View
and customizing the toolbar. This is the path tool which you can add to
the top of your window which will allow you to see this information.
In this video, Professor White shares four tips that will help save you time
when working with commands and files in the terminal.
Video Transcript
Now that you know how to use the terminal on Mac, it'd be nice to learn
some cool, important tricks. These tricks aren't really necessary to work
with Python — you can get through the entire course without them — but
you'll find that they'll actually speed up a lot of the tasks that you want to
work on and will make some things that would normally be annoying not
so annoying. One of the first tricks we'd like to teach you is tab
completion. Right now I have the Terminal open where its Active
Directory is the Desktop. If I look on the Desktop, you'll notice that I have
a single folder, CIS551. I want to go inside of this folder. I would do that
by typing the "cd" command, space, and now I'm going to type the letter
c, but I'm not going to type anything else. Instead what I'm going to do is
I'm going to hit Tab, and now the Terminal has completed that
information for me. That's because there was only one thing available
that started with the letter c, so when I hit Tab, it knew how to complete
that to give me the final name of the folder. I can hit Return, and now I'm
inside of CIS551 and I can see the file and the two folders. I'd like to do
this again. I'd like to go inside of module1. I'm going to type "cd", space,
"m", and now I'm going to hit Tab. This time you'll notice that it stopped at
the word "module." That's because there are two folders in this directory
— one called module1 and the other one called module5 — and the
Terminal didn't know which one I meant. It was able to fill in as much
details as it could, but now it expects me to complete the rest of it. I'm
going to type the 1, and now I'm in the correct folder.
© 2019 eCornell. All rights reserved. All other copyrights, trademarks, trade names, and logos are the sole property of their respective owners.
Python Fundamentals
Cornell Computing and Information Science
Another nice trick is using the up and down arrows. If I type the up arrow,
you'll notice that I have now seen the command "ls", which was the
previous command that I typed. If I type the up arrow again, I get "cd
module1," which was the command that I typed two steps ago. If I do the
down arrow, I now return to "ls" because that was the previous command
that I typed. Using the up and down arrow keys, you can navigate what is
known as your command history. This is very, very useful when you're
repeating tasks over and over again, which we will find ourselves doing
later in the course. Finally, a very nice trick is to use the Command
hotkey to type Command-K. When I do that, you'll notice that it will clear
my entire screen. When you're working with Python for a long time, the
Terminal will be filled with lots of information; possibly error messages,
possibly the result of programs that I've run. Periodically, to keep myself
from being confused, I just want to start with a clean slate, and I can do
that by typing the Command-K key at any given time. Finally, the most
important trick is what is known as the drag-and-drop trick. A lot of times
that we're working with Python on our computer, we'll discover that the
files that we want are located inside of folders, inside of folders, inside of
folders. Here on my desktop I have CIS551, inside of that I have the
folder module1 and inside of that I have the folder folder1, and I want to
be able to access the script script1 in this particular folder. If I were to do
that, that's a lot of "cd" commands, and that can be really annoying. So
instead, what I'm going to do is to take folder1, which is the folder that I
would like my Terminal to be inside. I'm going to take this folder and I'm
going to drag it over to the Terminal that is located on my dock and I am
going to release it on the Terminal. When you do that, you will notice that
a new window has popped up. If I type "pwd", it is immediately in the
folder that I wanted. This is going to be a very, very fast way for us to
open up a Terminal window in the correct directory that we want, and
we'll find this to be very useful later in the course.
© 2019 eCornell. All rights reserved. All other copyrights, trademarks, trade names, and logos are the sole property of their respective owners.
Python Fundamentals
Cornell Computing and Information Science
Next, download the file module1.zip and put it on your Desktop. You
should unzip the folder. On most MacOS and most Linux variants, you
can do this by double-clicking the file. On Windows, you will need to right-
click the file and select Extract All.
This folder is exactly the same as the module1 folder in Codio from the
last assignment. We want you to do the following:
When you are done, take a screenshot of your command shell side by
side the graphical window for folder3. On MacOS, this will look something
like this:
© 2019 eCornell. All rights reserved. All other copyrights, trademarks, trade names, and logos are the sole property of their respective owners.
Python Fundamentals
Cornell Computing and Information Science
© 2019 eCornell. All rights reserved. All other copyrights, trademarks, trade names, and logos are the sole property of their respective owners.
Python Fundamentals
Cornell Computing and Information Science
Video Transcript
Now that you know how to use the Terminal, we're ready to start working
with Python. Python is a scripting language. That means that it is
designed to automate tasks on your computer. Now, any scripting
language needs to be able to work with the files and folders on your
computer, and Python does that through the Terminal. That means that
whenever we work with Python, we have to use the Terminal. On the
screen here, we're looking at the Terminal inside of Codio. If we want to
access Python, we just type the word "python" and hit Return. You'll
notice that some information is shown on the screen showing us the
version of Python that we're using, and there are these three greater-
thans on the screen. This is a prompt, just like the prompt in the
Terminal, that's waiting for me to type Python code. We're just going to
type something very simple here, like "1+1." Python does the calculation
and it tells us that the answer is 2. Now, while this looks a lot like the Unix
prompt, it is not the same thing. If I were to type Unix commands like "ls"
or "cd" or "pwd", Python wouldn't know what I'm talking about. That's
because it is a completely different program, even though it's using the
same window as the Terminal. If I want to go back to the normal
Terminal, I will have to quit Python. You do that by typing the word "quit,"
but after the word "quit," you have to remember to type two parentheses.
Now, once again, you'll notice that I'm back in the Terminal. I can see
that I'm in the workspace. The key thing to tell, are you in the Terminal or
are you in Python, is to look at the prompts. Here, I can see the dollar
sign; that tells me that I'm in the normal Terminal. When I'm running
Python, I see the three greater-thans, and that tells me that I'm in a
different environment than the normal Terminal. Now, Python, when I'm
running it this way, only allows me to type one command at a time, and
© 2019 eCornell. All rights reserved. All other copyrights, trademarks, trade names, and logos are the sole property of their respective owners.
Python Fundamentals
Cornell Computing and Information Science
© 2019 eCornell. All rights reserved. All other copyrights, trademarks, trade names, and logos are the sole property of their respective owners.
Python Fundamentals
Cornell Computing and Information Science
© 2019 eCornell. All rights reserved. All other copyrights, trademarks, trade names, and logos are the sole property of their respective owners.
Python Fundamentals
Cornell Computing and Information Science
cd - Changes directory
ls - Lists files
When running Python, you should see ">>>", which means you're in a
different environment from the normal terminal. If you see a dollar sign
"$", this means you are in the normal terminal.
To access a file, you may have to change to a different folder using the
"cd" command.
Use the command "ls" to see if you are in the correct directory.
To run a file, type "python", a space, and then the name of the file. Then,
hit Return. For example, to run a script called script.py, type python
script.py and hit Return.
© 2019 eCornell. All rights reserved. All other copyrights, trademarks, trade names, and logos are the sole property of their respective owners.
Python Fundamentals
Cornell Computing and Information Science
Once you've run a script, you can't type any more Python. When running
a script, all the commands in the file will execute and then Python will
quit.
© 2019 eCornell. All rights reserved. All other copyrights, trademarks, trade names, and logos are the sole property of their respective owners.
Python Fundamentals
Cornell Computing and Information Science
© 2019 eCornell. All rights reserved. All other copyrights, trademarks, trade names, and logos are the sole property of their respective owners.
Python Fundamentals
Cornell Computing and Information Science
Video Transcript
In this video, we're going to show you how to install Python on Windows.
Now, Windows is not a Unix machine, so therefore it's going to have a
slightly different installation than other platforms. But with that said, once
Python is installed, it should act the same as it does in Codio and in other
environments. Now, hopefully with these installers, you shouldn't have
any problem. But we understand that things happen. If you run into any
troubles at all, you should follow the instructions on the Canvas page;
that will connect you with someone to guide you through the process.
Now, one of the first things that I like to do before I install something like
Python is just find out, do I have Python installed at all? Typically,
Windows machines don't come with Python, but you might have installed
another piece of software that came with Python in it. To find out whether
or not you have Python, we can just start up the PowerShell like I have
here, and type the command "python" and hit Return. Ah, you'll notice
that the PowerShell here gives me a lot of angry red text; that's just
telling me that I don't have Python installed, so I'm going to have to install
it.
Now, when I install Python, I have a lot of options. One of the things that I
could do is I could just go to the main Python website, www.python.org.
When I go there, I can click on the Downloads link, and this case it
© 2019 eCornell. All rights reserved. All other copyrights, trademarks, trade names, and logos are the sole property of their respective owners.
Python Fundamentals
Cornell Computing and Information Science
There's one last thing that Anaconda is going to pester us with. It's going
to ask us to install Microsoft VS Code. You can install that if you want to,
but it's not really necessary. We're actually going to use an alternate
program that's a lot like VS Code in Module 5. But for right now we don't
need this. We're going to skip, and now the installation has finished. Let's
go over to the PowerShell and let's check to see that we have Python.
We'll type "python", and now you can see that Python is fully installed.
There's one last thing that we need to do with our installation. As we've
mentioned, one of the reasons why we would like to be able to have a
new version of Python is because we want to put in third-party add-ons.
There's a very important third-party add-on that we're going to use for this
course; it's called IntroCS. This is a package that's been developed here
at Cornell that's used for our introductory courses. We're going to install
this with the "pip" command. pip is the Python Package Manager. To use
pip, we're going to take the PowerShell and we're going to type the
command "pip install", and now the thing that we want to install is
IntroCS. Now we're going to hit Return. You'll notice that there are a
bunch of commands that come on the screen, but at the end it says that I
have successfully installed IntroCS. If I want to check that it works, I type
"python" and now I can type "Import IntroCS". It doesn't seem like
anything happens. We'll talk about this meaning of what we've just done
here later in the course. But the fact that there is no error message tells
me that I've installed IntroCS properly. So now I'm done with my
installation on Windows.
© 2019 eCornell. All rights reserved. All other copyrights, trademarks, trade names, and logos are the sole property of their respective owners.
Python Fundamentals
Cornell Computing and Information Science
Video Transcript
In this video, we're going to show you how to install Python on the
Macintosh. If you're using a Linux machine, the installation steps are
roughly the same because they're both Unix operating systems.
However, if you're using Linux, you might want to use a Package
Manager instead. Regardless of whether or not you're using this
installation that we show you or a Package Manager, hopefully
everything goes smoothly, but we understand that problems sometimes
happen. If you're having trouble installing Python on your computer,
please follow the instructions on the Canvas page. That link will connect
you with someone to guide you through the process. Now, the thing
about Unix machines is they typically come with Python installed. The
first thing you should always do is to check what version of Python is on
your computer. Right now we have a Terminal open and we're going to
start Python by typing the "python" command. As you can see, this
computer already has Python installed. It's the Apple version of Python,
which we can tell by the message that is displayed on the screen. That's
not so interesting. The important thing is the Python version. You'll notice
that this is Python version 2.7, which is a very old version of Python. In
this course, we need to work with Python 3; specifically, we need to have
Python 3.5 or greater. It's not necessary that you have the latest or
greatest or fanciest Python, but there were a lot of features that were
added in Python 3.5 that are necessary for this course. Right now, Apple
only ships with Python 2.7. However, if you obtain a newer operating
© 2019 eCornell. All rights reserved. All other copyrights, trademarks, trade names, and logos are the sole property of their respective owners.
Python Fundamentals
Cornell Computing and Information Science
system that has Python 3 installed, it's still not clear that you want to use
the official Apple version. Apple uses its Python version for operating
system tasks. And for security reasons, it doesn't like it when you install
third-party add-ons into its Python. Because we're going to rely on third-
party add-ons in this course, we're going to install a second copy of
Python onto our computer.
Now when you're installing Python, there's several options. You can just
install the default version of Python by going to www.python.org. When
we go to this web page, you will notice that right away it can tell that I'm
running a Macintosh computer and it gives me a download link for Python
3.7. Again, we don't have to have Python 3.7, but it is at least Python 3.5,
so that's good and we can download this link. There's another version of
Python that actually we recommend here at Cornell, and that is
Anaconda Python. The vanilla Python that you get from python.org is
very, very bare-bones, and while it works, it doesn't have a lot of things
installed in it. Anaconda is a very feature-rich Python distribution, which
includes a lot of nice things for data science. It has many, many
packages already pre-installed, and so it makes the installation easier. If
you're thinking about taking other courses here with eCornell that work
with Python, we recommend that you install Anaconda. If we go to
Anaconda's web page, we will notice that there's a link here to download
Anaconda. We will click on it, and it will now take us to an area where we
can make a choice. We can either choose Python 3.7 or Python 2.7.
Once again, in this course, we're always working with Python 3, so we
would choose the one that is on the left. Now, I've already downloaded
both of these distributions, and if I go to my Downloads folder, I can see
both the Anaconda installation package as well as the vanilla Python
installation package. I'm going to take us through the Anaconda
installation, but the vanilla Python installation is very, very much the
same. We're going to double-click on the installer and it's going to give
me some legalese before I install, just like any other installer. Now, I'm
going to reach the point where it tells me that it's going to take 2.2 gigs of
space on my computer, and you'll notice that before I click the button for
install, I have the option to change the install location. This isn't
necessary, but I like to do this; in particular, because right now the default
is to install Anaconda for me only. That makes sense if you're the only
person using this computer. But if you have a computer that has multiple
accounts on it — perhaps you're sharing your computer with other people
© 2019 eCornell. All rights reserved. All other copyrights, trademarks, trade names, and logos are the sole property of their respective owners.
Python Fundamentals
Cornell Computing and Information Science
Now when we start Python, you'll notice that now we are indeed running
Python 3.7, which is the right one that we want to use. If there's ever any
doubt about which version of Python you are running, you can always
type the command "which", followed by the world "python", and it will tell
us that in this case I'm running Python which is located in the anaconda3
folder which is located inside of Applications. Before we're done, there's
one last thing that we have to do. There is, as I said, a third-party add-on
that we need to add for this course. This is the IntroCS package, which is
a package that was developed here at Cornell for people who are starting
off with Python. We're going to install this with pip, which is the Python
Package Manager. To install IntroCS, we type the word "pip", the word
"install", and then "introcs", which is what we want to install. We hit
Return, and now you will notice that there are couple of error messages
here on the screen, but nothing really important; it's just claiming that I
need to update my version of pip. That's not necessarily important. What
is important is you'll notice that it says that it has successfully installed
IntroCS. Once I have done this, I have now completed my installation.
© 2019 eCornell. All rights reserved. All other copyrights, trademarks, trade names, and logos are the sole property of their respective owners.
Python Fundamentals
Cornell Computing and Information Science
Installing Python
Now that you have finished Executing Python in the Codio environment, it
is time to try it on your own computer. First, you should install Python 3
on your computer (the default Python installations on MacOS and Linux
are often Python 2). We recommend one of two options:
Standard Python
Anaconda
Make sure to get a version that is 3.5 or higher. The most recent number
is not always the best, however, as it may be experimental.
Once it is installed, you need to install the introcs package. You do this
with pip. Open up the command shell on your computer and type:
This will install the introcs package, which is the only additional package
we will need for this course.
Once installation is complete, return to the module1 folder you created for
Navigating Your Computer. Again, navigate to folder3 and do the
following:
When you are done, take a screenshot of your command shell side by
side the graphical window for folder3. On MacOS, this will look something
like this:
© 2019 eCornell. All rights reserved. All other copyrights, trademarks, trade names, and logos are the sole property of their respective owners.
Python Fundamentals
Cornell Computing and Information Science
Note for Mac users: If you have installed a Python version newer
than 3.6.6, do not run the hello_app.py script on your machine, as it
may cause a crash.
© 2019 eCornell. All rights reserved. All other copyrights, trademarks, trade names, and logos are the sole property of their respective owners.
Python Fundamentals
Cornell Computing and Information Science
© 2019 eCornell. All rights reserved. All other copyrights, trademarks, trade names, and logos are the sole property of their respective owners.
Python Fundamentals
Cornell Computing and Information Science
© 2019 eCornell. All rights reserved. All other copyrights, trademarks, trade names, and logos are the sole property of their respective owners.
Python Fundamentals
Cornell Computing and Information Science
After each of these videos, you will be given assignments that require
you to execute Python code and type the results into a form. You may
execute this Python code on your own machine or in the provided
sandbox, whichever you prefer.
© 2019 eCornell. All rights reserved. All other copyrights, trademarks, trade names, and logos are the sole property of their respective owners.
Python Fundamentals
Cornell Computing and Information Science
Video Transcript
Now that you know how to start Python, it's time for us to do something
cool: It's time for us to start programming in Python. Now, the programs
that we're going to write are going to be really simple; they're probably
only going to be about one line. But with that said, I mean, that's still
having Python do some interesting calculations. Now, before we do any
of this, we have to understand three important concepts. Those concepts
are expressions, values, and types. Now what is an expression? An
expression is something that I type into Python. In an earlier video, you
saw me start up Python, and after the three greater-thans, I typed "1+1."
This is an example of an expression; it's some sort of mathematical
formula. Another example of an expression might be just a simple
number, like 23. Can even do something other than numbers, like text, by
writing the word 'hello' in between two apostrophes. Now, when I give
Python an expression and I hit Return, Python gives me something back.
In this case, I typed "1+1" and it gave me the number 2. The thing that it
showed me back, the 2, is what is known as a value. An expression
represents something, and what Python does, it evaluates it, or turns it
into a value. If you think about it, this is essentially what a calculator
does. You type in some sort of mathematical formula with the buttons,
you hit either the equal sign or an Enter button, and it gives you
something back. So in this case, I typed in "1+1", which is the expression,
and I got the value 2 back. If I type "23," you'll notice that Python gives
me the number 23 back. However, once again, these are not the same
thing. The 23 that I typed after the three greater-thans is an example of
© 2019 eCornell. All rights reserved. All other copyrights, trademarks, trade names, and logos are the sole property of their respective owners.
Python Fundamentals
Cornell Computing and Information Science
Now, as I said, not everything that we're going to be working with with
Python is necessarily a number. However, everything underneath the
hood turns into numbers. So the text that I have on the screen, Python is
storing in its memory as numbers. If I were doing a graphical application
where I'm working with colors, those would be represented by numbers
as well; particularly the numbers for the red, blue, and green colors. And
there are other types of data that I might be working with on Python. So
one of the things that we have to worry about is that how does Python tell
all of these things apart? How does it know that I want to be working with
numbers, or I want to be working with text, or I want to be working with
colors? This is the idea behind a type. A type is a set of values and the
operations on them. So when I talk about operations, I just mean things
like plus, or times, or divides. So when I have "1+1," the one is an
example of an int type. It is an integer, and the things that I can do with
integers is that I can add them or multiply them. Text, which are inside of
these apostrophes, can be added, but they can't be multiplied. So they
have a very different set of operations behind them. So that's why they
are a different type. Throughout this entire module, what we're going to
be doing is we're going to use Python as a very simple calculator. We're
going to be writing expressions for Python to evaluate, and then we're
going to get an answer back as a value. You can either do this on your
computer, or you can be using the Codio Sandbox to do these activities if
you prefer to use that. But in order to do all of these things, we first need
to learn the basic types. We're going to learn each individual type that's in
Python, what operations are available for that type, and how they work.
You should think of this as a form of vocabulary building. And once we
have this vocabulary, we're going to be able to write more interesting
programs in later modules in this course.
© 2019 eCornell. All rights reserved. All other copyrights, trademarks, trade names, and logos are the sole property of their respective owners.
Python Fundamentals
Cornell Computing and Information Science
© 2019 eCornell. All rights reserved. All other copyrights, trademarks, trade names, and logos are the sole property of their respective owners.
Python Fundamentals
Cornell Computing and Information Science
An expression is something that you type into Python. For example, the
number "23" or "1+1" both qualify as expressions. A value, on the other
hand, is something that Python returns once you've executed an
expression. As Professor White explained, humans type expressions and
Python produces values.
A value can be many different things, though. How does Python know
when you want to be working with numbers, or text, or colors? This is the
idea behind a type. A type is a set of values and the operations on them.
Using the method type() will show you what type the value is. There are
several different data types in Python, including the following:
© 2019 eCornell. All rights reserved. All other copyrights, trademarks, trade names, and logos are the sole property of their respective owners.
Python Fundamentals
Cornell Computing and Information Science
© 2019 eCornell. All rights reserved. All other copyrights, trademarks, trade names, and logos are the sole property of their respective owners.
Python Fundamentals
Cornell Computing and Information Science
Video Transcript
One of the most important types in Python is int, for the integers.
Remember that a type is a collection of values and the operations on
those values. The values for type int are just positive and negative whole
numbers. If I want to put an int into Python, I just type it, "12" gives me
the number 12. If I wanted negative 12, I just type a minus sign and "12."
The important rule to understand about integers is that you're just typing
the digits. You don't want to have a decimal in an integer. 12.5 is not an
integer; that is a very different type that we will address in another video.
In addition, for very large integers, you don't want to put any commas in
them. If you do that, well, Python'll give you something weird back, but
actually what it gives you back is beyond the scope of this course. So, all
you should do, if you want a very large number, is just type the digits by
themselves. Now, the operations on integers are just the standard
mathematical operations. We've already seen that we could add two
integers together. We can subtract one integer from another. We can
also multiply integers. If we want to multiply one integer times another,
we use the asterisk. So this is "3*4", which gives me the answer of 12. If I
were to use two asterisks in between 3 and 4, this is used for
exponentiation. This would raise 3 to the power of 4, which in this case is
81. The most interesting operation for integers is division, because it
behaves a little differently than you would expect division to behave. So
suppose I want to divide 1 by 2. The way you divide with integers is you
don't give it a single slash; you have to give it two slashes. So "1//2". The
reason why we have to handle this differently is operations on two
integers should also produce an integer. So normally you would say, "Oh,
1 divided by 2 must be 0.5." But 0.5 is not an integer. When I do this
double slash, when it divides 1 by 2, you'll notice that it gives me the
answer zero. Why is that? Because now you should go back to grade-
© 2019 eCornell. All rights reserved. All other copyrights, trademarks, trade names, and logos are the sole property of their respective owners.
Python Fundamentals
Cornell Computing and Information Science
school division, and you just think, like, how many times does one
number go evenly into another? 2 can't go into 1 at all. If I were to say 3
divided by 2, well, 2 can evenly go into 3 one times, and therefore it gives
me the answer 1 back. Then again, like grade school, we might want to
say, "Oh, does that mean that we can somehow find the remainder when
we divide?" And yes, we can. That is yet another operator, which is
known as the percent operator. So if I say "3 % 2", that gives me 1,
because 1 is the remainder when I divide 3 by 2. Now, you may see
some examples online where people use a single slash to divide one
integer by another. However, that's not supported in Python 3; that's a
Python 2 version. So you should always be cognizant when you're
looking at examples online whether or not it's an example from Python 2
or Python 3.
© 2019 eCornell. All rights reserved. All other copyrights, trademarks, trade names, and logos are the sole property of their respective owners.
Python Fundamentals
Cornell Computing and Information Science
© 2019 eCornell. All rights reserved. All other copyrights, trademarks, trade names, and logos are the sole property of their respective owners.
Python Fundamentals
Cornell Computing and Information Science
In this video, Professor White introduces the float type and explains why
Python has multiple numeric types.
Video Transcript
One of the most important types in Python is int, for the integers.
Remember that a type is a collection of values and the operations on
those values. The values for type int are just positive and negative whole
numbers. If I want to put an int into Python, I just type it, "12" gives me
the number 12. If I wanted negative 12, I just type a minus sign and "12."
The important rule to understand about integers is that you're just typing
the digits. You don't want to have a decimal in an integer. 12.5 is not an
integer; that is a very different type that we will address in another video.
In addition, for very large integers, you don't want to put any commas in
them. If you do that, well, Python'll give you something weird back, but
actually what it gives you back is beyond the scope of this course. So, all
you should do, if you want a very large number, is just type the digits by
themselves. Now, the operations on integers are just the standard
mathematical operations. We've already seen that we could add two
integers together. We can subtract one integer from another. We can
also multiply integers. If we want to multiply one integer times another,
we use the asterisk. So this is "3*4", which gives me the answer of 12. If I
were to use two asterisks in between 3 and 4, this is used for
exponentiation. This would raise 3 to the power of 4, which in this case is
81. The most interesting operation for integers is division, because it
behaves a little differently than you would expect division to behave. So
suppose I want to divide 1 by 2. The way you divide with integers is you
don't give it a single slash; you have to give it two slashes. So "1//2". The
reason why we have to handle this differently is operations on two
© 2019 eCornell. All rights reserved. All other copyrights, trademarks, trade names, and logos are the sole property of their respective owners.
Python Fundamentals
Cornell Computing and Information Science
integers should also produce an integer. So normally you would say, "Oh,
1 divided by 2 must be 0.5." But 0.5 is not an integer. When I do this
double slash, when it divides 1 by 2, you'll notice that it gives me the
answer zero. Why is that? Because now you should go back to grade-
school division, and you just think, like, how many times does one
number go evenly into another? 2 can't go into 1 at all. If I were to say 3
divided by 2, well, 2 can evenly go into 3 one times, and therefore it gives
me the answer 1 back. Then again, like grade school, we might want to
say, "Oh, does that mean that we can somehow find the remainder when
we divide?" And yes, we can. That is yet another operator, which is
known as the percent operator. So if I say "3 % 2", that gives me 1,
because 1 is the remainder when I divide 3 by 2. Now, you may see
some examples online where people use a single slash to divide one
integer by another. However, that's not supported in Python 3; that's a
Python 2 version. So you should always be cognizant when you're
looking at examples online whether or not it's an example from Python 2
or Python 3.
© 2019 eCornell. All rights reserved. All other copyrights, trademarks, trade names, and logos are the sole property of their respective owners.
Python Fundamentals
Cornell Computing and Information Science
© 2019 eCornell. All rights reserved. All other copyrights, trademarks, trade names, and logos are the sole property of their respective owners.
Python Fundamentals
Cornell Computing and Information Science
In this video, Professor White first introduces the Boolean type, or bool,
which deems statements as either true or false, then introduces
comparison operations as a way for Python to evaluate expressions.
Video Transcript
Python also has types that don't involve numbers at all. Python has a
type called Bool, which is short for Boolean. There are only two Boolean
values; they're "True" and "False." And if I just want Python to use those,
I would type those words. If I type "True", Python recognizes this as the
value "True." If I type the word "False", Python recognizes this as the
value "False." Now, capitalization is important here. If I type "true" all
lowercase, then Python doesn't know what I'm talking about. Now, Bools
are very simple. Not only do they just have two values, but they only have
three operations: "not", "and", and "or". "Not" is what is known as a unary
operation; it's something that I only do to a single Boolean. So if I type
something like "not True", what Python's going to do is it's going to take
the "True" and flip it around to its opposite, which is "False"; and similarly,
"not False" is "True." "And" and "or" are what are known as binary
operations. They take two Booleans and combine them together to give
me a third, much like plus and times do with numbers. "True" takes the
two Booleans and looks at them, and if they're both "True", then it's going
to evaluate that to the value "True." However, if just one of them is
"False", the answer that it's going to evaluate to is "False." "Or" is similar
but opposite; it only needs one of the two sides to be "True". However, if
they're both "False", then it's going to evaluate to "False." Now, one of
the things we have to be careful about with "or" is the way that we use
"or" in English is sometimes a little different than the way "or" works in
Python. A lot of times when we use the word "or," we mean, "Oh, exactly
one of these." But Python, when it looks at "or", it just needs at least one
of the two sides to be "True". So "True or True" evaluates to "True." And
© 2019 eCornell. All rights reserved. All other copyrights, trademarks, trade names, and logos are the sole property of their respective owners.
Python Fundamentals
Cornell Computing and Information Science
that's all there is to know about Boolean, so you might look at this and
you're going to say, "Why do I need Python to do computations on things
this simple?" It's because we're not usually typing the words "True" and
"False" into Python; we're getting these from other expressions. So
returning to the number types that we've seen before, like int and float,
there's another group of operations on them called the comparison
operations. And they're what you think. If I type the less-than symbol
between two numbers, what Python's going to do is it's going to give me
an answer of "True" or "False" indicating whether or not that comparison
is true. So in this case, since 1 is less than 2, I get an answer of "True."
On the other hand, if I type "2<1", Python is going to tell me that that
answer is "False." There are several comparison operations. In addition
to the less-than that you expect, there's also a greater-than. There's also
a less-than-or-equal, which I get by typing two symbols — the less-than
symbol first, and then the equal sign — and there's also a greater-than-
or-equal. I can also just — instead of just asking whether or not two
numbers are less than one another or greater than one another, I can just
ask, are they equal? I do that by typing two equal symbols. This is very
important. If I just type one equal symbol, I'm going to get an error, and
that's because Python means something very different — which we'll talk
about in a different module — when I type a single equal sign. Another
thing that you should be concerned about with double equals is that we
have to be very careful with this on floats. Remember that when we
talked about floats, we've mentioned the issue of round-off error or
representation error. And that's the reason why, when you try to compare
two floats to one another, you don't always get the answer that you
expect. However, because ints are always exact, well, those
comparisons are always relatively accurate. In addition to the double
equals, I can also type an exclamation mark and equal symbol. In this
case, what Python interprets this as, not equals. So since 1 is not equal
to 2, I get an answer of "True." Now, that I have these comparison
operations, there are lots of things that I can do with these "and" and "or"
operations. I can build fairly interesting expressions, like "(1<2) and
(2<1)", and have Python evaluate them. You'll notice that Python has
given me the value "False" here; that's because while "1<2" evaluates to
"True," "2<1" evaluates to "False." And remember, in the case of "and",
both sides have to be true in order for it to be true.
© 2019 eCornell. All rights reserved. All other copyrights, trademarks, trade names, and logos are the sole property of their respective owners.
Python Fundamentals
Cornell Computing and Information Science
© 2019 eCornell. All rights reserved. All other copyrights, trademarks, trade names, and logos are the sole property of their respective owners.
Python Fundamentals
Cornell Computing and Information Science
© 2019 eCornell. All rights reserved. All other copyrights, trademarks, trade names, and logos are the sole property of their respective owners.
Python Fundamentals
Cornell Computing and Information Science
In this video, Professor White describes the type used exclusively for
text, string, and some of the ways to work with text using this type.
Video Transcript
So far, we've used Python as a calculator, you know, working with things
like numbers. But one of the things that Python is really good at is text
processing. So therefore it makes sense for Python to have a type that
has to deal with text. That type is called a "string," or str, for short. The
values for a string are any sequence of characters. Now, what is a
character, you might ask? A character is anything that we might type in
text. So obviously it includes letters, but it might also include spaces,
punctuation. These days, depending on your computer, it can even
include emoji. The idea is if you can type it, it's likely a character. But that
means that we need some way to distinguish text from numbers, like int
or float. In fact, if I just type text into Python, like, say, the word Hello,
Python gets confused; it gives me an error message. Doesn't know what
I'm talking about. To let Python know that I'm giving it text that needs to
be processed, I have to give it between two quotes. I can use single
quotes, so here I have 'Hello' inside of single quotes, and Python is
happy, I can also use double quotes. Python doesn't really care; each of
those are the same. And in fact, if you'll notice that when I typed in
double quotes, Python said, "Well, you could have used single quotes
instead," and that's what it gives me back as a value. But this is why this
is important. Suppose I want to talk about the number 3. If I type 3 by
itself, Python realizes it is an int. On the other hand, if I take 3 and I put it
between two quotes, Python knows that, "Oh, I have some text that
needs to be processed, and 3 is part of that text."
Now, another thing to understand about strings is how Python works with
them. Essentially behind the scenes, Python treats each character in a
© 2019 eCornell. All rights reserved. All other copyrights, trademarks, trade names, and logos are the sole property of their respective owners.
Python Fundamentals
Cornell Computing and Information Science
Now, these are what the values of a string are, but remember a type is
values plus operations. There are essentially two operations with Python.
The first is plus, just like adding numbers, but adding strings is a little
different. Let's suppose I have two strings, 'ab', and I want to add
together it to the string 'cd'. You'll notice that when I type this into Python,
I get back the string 'abcd'. Once again, let's think about our visualization.
The first string, 'ab', is two boxes with an a and a b. The second string is
two boxes with a c and a d When I plus them together, what Python does
is it pushes those together to create four boxes: a, b, c, and d. Another
thing to understand about plus is I might have a string, say 'ab', and now
I'm going to add together to it the string ' '. Notice that I get back the
string 'ab' by itself. What is this ' '? Well, the first string, 'ab', is it's two
boxes; a and a b. If I have nothing inside of the quote, I'm telling Python I
don't have any boxes. This is what we call the empty string. In some
sense, you can think of this acting like 0 with numbers. And as we'll see
in a later module, it's useful in the same way that the number 0 is. So
that's plus, which is one operation. The other operation is in. In is a
comparison operation. I can ask "'a' in 'ab'", and notice that I'll get back
the Boolean value "True." What this operation does is it takes the first
string and it asks, "Is it inside of the second string?" So the first string is
© 2019 eCornell. All rights reserved. All other copyrights, trademarks, trade names, and logos are the sole property of their respective owners.
Python Fundamentals
Cornell Computing and Information Science
'a', which is a single box. The second string is 'ab', which is two boxes, a
and b. And since there is a box containing a inside of ab, I get the answer
"True." On the other hand, if I ask, "Is x inside of ab?" I'll get the answer
"False." Now, when I use the comparison in, I'm not limited to looking at a
single letter; I can ask, "Is ab inside of abc?" Once again, I'll get the
answer "True" here, and that's because the two boxes, a and b, are
inside of the three boxes a, b, and c. On the other hand, if I ask, "Is ac
inside of abc?" I'll get the value "False." And that's because even though
the individual values a and c are inside of abc, I don't have two boxes
right next to each other which are a and c.
© 2019 eCornell. All rights reserved. All other copyrights, trademarks, trade names, and logos are the sole property of their respective owners.
Python Fundamentals
Cornell Computing and Information Science
Video Transcript
In a previous video, we talked about strings and how strings are
composed of characters. Now, characters obviously include letters, but
we pointed out that they can contain other things like punctuation. So, for
example, instead of just typing the word Hello, I could tack an
exclamation mark on the end and make that part of the string. And as a
string, this would now be six boxes: an H, an e, an l, an l, an o, and then
finally, an exclamation mark. Now, punctuation creates a really
interesting problem because quotes count as punctuation as well. So
what if I want to put a quote inside of a string? Before we type anything
into Python, let's try to visualize the word Don't. This would be five boxes.
It would be the letter D, an o, an n, an apostrophe — which is really a
quotation mark — and a t. So now let's think about how we would type
this in Python.
© 2019 eCornell. All rights reserved. All other copyrights, trademarks, trade names, and logos are the sole property of their respective owners.
Python Fundamentals
Cornell Computing and Information Science
knows that that thing is an apostrophe simply because it knows that the
string started with double quotes, so it has to end with double quotes as
well.
OK; well, this is fine, but it doesn't always solve the problem. Let's
suppose I want to talk about a string like 'say "Hello"'. So this has several
characters, but let's go spell this out. I'll have an s, an a and a y, space.
And now I'm going to have some quotes because I'm talking what
somebody is saying. So I have a double quote, an H, an e, an l, an l, and
an o, and I'm going to end with double quotes. All right. So all of these
things are parts of the string. Now let's try to type this. So if I try to do this
with double quotes, "say "Hello"", you'll notice that once again I get an
error. Because I've started with double quotes, Python knows that the s,
the a, the y, even the space are part of the string. But those double
quotes before the Hello, that thinks that that's the end of the string. So
now it's confused and it doesn't know what to do. Once again, we can
solve the problem by using single quotes instead. So 'say "Hello"', and
now Python knows what I'm talking about because it knows that those
double quotes are part of the string because the single quotes were used
to start and end the string. But now we have a problem if we combine the
two. So let's suppose we're not saying Hello, but we're saying the word
Don't. So now let's visualize this first before we do anything. So we're
going to have several boxes; an s, an a, a y, a space. Now I'm going to
have a double quote. I'm going to have the D, the o, the n, the
apostrophe, the t, and the double quote. So now let's think about how we
would write these. So if I did it with double quotes, "say "Don't"", that
doesn't work because it realizes that the string begins at s-a-y and the
space, but then when it hits that double quote inside of the string, it
doesn't know what to do. If I do it with single quotes, 'say "Don't"', once
again, I get an error because — well, it gets a little farther this time; It
sees the s, the a, the y, the space. The double quote is fine, since we
began with a single quote. The D, the o, the n, but now it hits the
apostrophe, and it doesn't know what to do.
So we can't solve this problem by going back and forth between our
choice of quote characters. So we had to come up with another solution,
and the solution is what is known as an escape character. An escape
character is essentially a way to tell Python that we don't want to use a
quote character to end a string, but we want to put it in its own box. And
© 2019 eCornell. All rights reserved. All other copyrights, trademarks, trade names, and logos are the sole property of their respective owners.
Python Fundamentals
Cornell Computing and Information Science
we do this with a backslash. So I'm just going to type in here; I'm going to
start Don't by itself, and I'm going to do instead with single quotes this
time. So the D, the o, the n. I'm about ready to type the apostrophe but I
don't want Python to think that I'm ending the string. So what I'm going to
type now is a slash, and I'm going to type my apostrophe. Now, the
important thing to understand here is this slash is not part of the string.
When Python is reading this, it's going to see the D, it's going to see the
o, it's going to see the n, but it's not going to put a slash; the next box is
going to be that apostrophe character. The purpose of the slash is to tell
Python to give the apostrophe character its own box. Now I can type t,
and I can end with quotes, and Python is happy. In fact, even Python
gives me a nice little reminder that "Oh, you didn't have to make it this
complicated; you could have used double quotes instead." Now, of
course, this means, well, if the backslash isn't part of the string, what if I
wanted to include the backslash in the string? Let's suppose I just wanted
to make a string with one box that has the backslash inside of it. So do I
type '\'? When I hit Return, you'll notice that I get an error here because
what I've just told Python is, OK, I've given it a slash, so I'm telling Python
that next quote, the one at the end, isn't the end of the string; it should go
into a box. And now it's expecting another quote to end the string, and it's
not seeing it. Well, once again, what you have to do is you have to use
an escape character. So if you want a single slash, you have to type two
slashes. Now, even though Python is displaying this as two slashes when
we type it in there, the thing to understand is there's only one box here.
This box contains a single slash in it. And that's because the first slash is
telling Python that the character after it is special. So in general, when we
talk about an escape character, we're talking about a slash, which is what
we call the escape, and a character after it, which is the special character
that we needed in order to tell Python to put it into a box. There are many
other examples of escape characters. There is \n, which is used to tell
Python that, "Hey, I want to take a string and I want to break it up into
multiple lines." Or \t, when I want to put a tab into something. So a lot of
escape characters are used for formatting text and making it pretty. So
this is something that we will work with a lot in a later module.
© 2019 eCornell. All rights reserved. All other copyrights, trademarks, trade names, and logos are the sole property of their respective owners.
Python Fundamentals
Cornell Computing and Information Science
© 2019 eCornell. All rights reserved. All other copyrights, trademarks, trade names, and logos are the sole property of their respective owners.
Python Fundamentals
Cornell Computing and Information Science
Video Transcript
Up until now, we've been working with very simple expressions. They've
either been literals, right, which are these expressions that when you type
them into Python you get the same thing back. Or they've been simple
expressions with just a single operation in them, like, say, multiplication.
But of course, we want to do more complex mathematical expressions,
things that involve multiple operations; say, both multiplication and
addition. But as we know from math, when we start adding parentheses
here, sometimes that can actually change the answer. In the second
example, I didn't get the answer 5; I got the answer 8 instead. Why is
that? Well, in the second example, I saw the parentheses. And I know
that whenever I see parentheses, I should do those first. So 1 plus 3 is 4,
and 2 times 4 is 8. However, in the first example, there aren't any
parentheses. So I know to multiply 2 times 1 first, which is 2, and then
add 3 to that to get 5. What we're talking about here is the concept of
operator precedence, which is the fixed order which Python uses to
process operators in the absence of any parentheses. You might have
learned something like this in grade school with an acronym called
PEMDAS. This stands for parentheses, exponentiation, multiplication,
division, addition, and subtraction, right? In the second example, I saw
the parentheses first; P comes first in PEMDAS. So I do the 1 plus 3 first,
before I do the multiplication. However, in the second example, M, for
multiplication, happens before A, for addition, so that is why we get the
answer 5 instead. Python uses exactly the same order. The only
difference with Python is that I have operations other than the simple
arithmetic operations. We have the comparison operations, like less than,
greater than, equals, not equals. And we also have the Boolean
© 2019 eCornell. All rights reserved. All other copyrights, trademarks, trade names, and logos are the sole property of their respective owners.
Python Fundamentals
Cornell Computing and Information Science
operations like "not", "and", and "or". In fact, in a previous video, we saw
an expression like this: "(1<2) and (2<1)". Python was able to evaluate
this with no error. In fact, it makes sense here; we see the parentheses,
we do that first. 1 is less than 2 is "True." 2 is less than 1 is "False." "True
and False" is "False." However, the thing to realize is that I didn't actually
have to type these parentheses here. And that's because the rule is
Python does PEMDAS first, then it does the comparison operations like
less than, and then the last thing that it does is the logical operations. So
in this case, it would do "1<2", which is "True," "2<1", which is "False,"
and then "and" would give us an answer of "False" as well. One of the
things that we've been doing in the assessments that you've been
working on is sort of getting you to understand these types of issues with
our expressions. I want to end with a slightly more interesting example.
So, I can combine arithmetic operations, like plus, with a comparison
operation, like less than. Once again, Python doesn't have any value —
problem with this; that's because it does the plus first, for PEMDAS. So 1
plus 2 is 3, 5 plus 7 is 12. And then after that, it does the comparison; so
3 is indeed less than 12, which is "True." On the other hand, let's
suppose I took that less than in the middle and I put parentheses around
it. You notice I don't actually get an error here. I get an answer, but it's
kind of a weird answer. Well, let's step our way through this. We see
parentheses, so we do that first. So this is 1 plus what's inside the
parentheses; 2 is less than 5 is "True." So what I typed is the same thing
as typing "1 + True + 7", which Python doesn't actually have any problem
with. The reason why is because what Python does in this case is it takes
the "True" and it turns it into 1. And that is indeed why we get the answer
of 9. This is what is known as type coercion, and this is going to be the
subject of the next video.
© 2019 eCornell. All rights reserved. All other copyrights, trademarks, trade names, and logos are the sole property of their respective owners.
Python Fundamentals
Cornell Computing and Information Science
Video Transcript
In a previous video, we saw this interesting expression where we had
addition but we combined integers and Booleans together. This "1 + True
+7", which Python didn't have a problem with; it gave us the answer of 9.
What's going on here is I have an expression that's mixing types, and I
don't have to do something fancy like this to mix types. I could do
something like mixing an integer and a float together, "1 + 3.5", in which
case, I get an answer that's a float. Now, we've also seen that it's not
always easy to mix type. Sometimes when we do that, like, say, adding
the text '2' to the number 2, I get an error. And so why is this? Why is it
that sometimes I get an error when I try this and sometimes I don't? It's
because when Python's working with operations like, say, plus, both of
the things around the plus have to have the same type. And if they don't
have the same type, then Python has to convert them so that they are.
So let's just look at this simple example, "1 + 3.5"; I'm adding an int to a
float. In order for Python to make sense to this, it either has to convert the
1 to a float or it has to convert the 3.5 to an int. The choice it's going to
make is it's going to convert the int to a float. And why? Because I'm not
really losing any information here; all I have to do is add a .0 to the 1. But
if I turn a 3.5 into an int, I have to drop off that .5 and I'm losing a lot more
information. So Python is always going to make a choice that doesn't
lose information. In fact, what can happen here is that Python can always
easily convert between a Boolean, an integer, and a float. It can't easily
convert these types to a string, and it can't easily convert from a string
back to these types. When it does this conversion, it does it from what we
call narrow to wide, right? Bool is narrow because there's only two
values, "True" and "False". It goes from Boolean to int, and then int has
© 2019 eCornell. All rights reserved. All other copyrights, trademarks, trade names, and logos are the sole property of their respective owners.
Python Fundamentals
Cornell Computing and Information Science
© 2019 eCornell. All rights reserved. All other copyrights, trademarks, trade names, and logos are the sole property of their respective owners.
Python Fundamentals
Cornell Computing and Information Science
© 2019 eCornell. All rights reserved. All other copyrights, trademarks, trade names, and logos are the sole property of their respective owners.
Python Fundamentals
Cornell Computing and Information Science
© 2019 eCornell. All rights reserved. All other copyrights, trademarks, trade names, and logos are the sole property of their respective owners.
Python Fundamentals
Cornell Computing and Information Science
© 2019 eCornell. All rights reserved. All other copyrights, trademarks, trade names, and logos are the sole property of their respective owners.
Python Fundamentals
Cornell Computing and Information Science
© 2019 eCornell. All rights reserved. All other copyrights, trademarks, trade names, and logos are the sole property of their respective owners.
Python Fundamentals
Cornell Computing and Information Science
In this video, Professor White first defines what a variable is, then shows
how visual metaphors are used to understand variables and the inner
workings of Python.
Video Transcript
© 2019 eCornell. All rights reserved. All other copyrights, trademarks, trade names, and logos are the sole property of their respective owners.
Python Fundamentals
Cornell Computing and Information Science
© 2019 eCornell. All rights reserved. All other copyrights, trademarks, trade names, and logos are the sole property of their respective owners.
Python Fundamentals
Cornell Computing and Information Science
Video Transcript
© 2019 eCornell. All rights reserved. All other copyrights, trademarks, trade names, and logos are the sole property of their respective owners.
Python Fundamentals
Cornell Computing and Information Science
Python has removed 5 from the box x and has replaced it with the value
7. So now, if I were to evaluate x, I would get a 7, and if I were to
evaluate x plus 2, I would get 9 instead. So now what we have to
understand is that this has sort of changed our model of Python a bit. In a
previous module, we were just typing one line at a time and Python was
giving us an answer back. Now what's happening is that we're typing a
sequence of lines in order, and the order that we type those lines is
important. Suppose I wanted to know — OK; let's evaluate what the
variable y is. I type this into Python; well, I'm going to get an error
because there is no variable y. Instead, what I'm going to do now is I'm
going to assign y is equal to 3. Again, that doesn't look like anything has
happened, but now this has created a new box, it's given the name y,
and it's put a 3 inside of it.
And now — and from this point forward — when I type y, I will be able to
see the value of 3. Another thing to understand about variables is that the
thing to the right of the equal sign does not have to be a literal; it can
actually be a more interesting expression. So I can type something like "x
= 2+4". What will happen is, Python is going to read this right to left, not
left to right. What it's going to do is it's going to evaluate the expression
on the right-hand side of the equal sign. In this case, it's giving me the
value of 6, and then it's going to put that inside of the variable x. I'll hit
Return; it's going to make that change to the box, and now when I look at
the variable x, I will get the value of 6 instead. The things on the right-
hand side of the equal sign can contain other variables. I can say "x =
y+1". What's going to happen? I'm reading this right to left; inside of the
box y is the value 3, 3 plus 1 is 4. When I type this, this is now going to
put the value of 4 inside of x. I can even type something like "x = x+2".
Now, some people might look at this and say, "Hey, this is a circular
definition." But it's not. Python reads, remember, right to left. So right now
I have the value of 4 inside of x. Reading this left to right, it's going to say
x is 4. I'm going to add 2 to it; that's going to give the value of 6. And now
what's going to happen is I'm going to replace that 4 inside of x with the
new value of 6. And indeed, when I look at x, that is indeed what has
happened.
© 2019 eCornell. All rights reserved. All other copyrights, trademarks, trade names, and logos are the sole property of their respective owners.
Python Fundamentals
Cornell Computing and Information Science
Creating Variables
This terminal is to assist you as needed. See below for instructions.
© 2019 eCornell. All rights reserved. All other copyrights, trademarks, trade names, and logos are the sole property of their respective owners.
Python Fundamentals
Cornell Computing and Information Science
In this video, Professor White explains that while variables in Python can
be many different combinations of characters, Python does have set
rules for naming variables.
Video Transcript
When I'm creating a variable, it doesn't have to be called a single letter,
right? Before we've talked about variables like x, but I could also have a
variable called "area." In this case, I'm going to create a variable "area"
and give it the value 20.1. To get the value of this variable, I just type the
word "area". I can even use the word "area" in an expression, like
"area+1". Python has very strict rules on how to create variable names.
These names are only allowed to contain letters, numbers, and the
underscore character. So I can name a variable "x2", I can name a
variable "x_2". I can also do things like put the underscore at the
beginning, so I could have "_a = 3". However, you are never allowed to
start a variable with a number. So I can't do "2x". In this case, Python
gives me an error because since I started with a number, it doesn't
realize that I'm actually talking about a variable. In particular, this is really
important, right, because e2 is a valid variable name, but 1e2, remember,
is the number 100, and I cannot use that as a variable name.
© 2019 eCornell. All rights reserved. All other copyrights, trademarks, trade names, and logos are the sole property of their respective owners.
Python Fundamentals
Cornell Computing and Information Science
Naming Variables
This terminal is to assist you as needed. See below for instructions.
© 2019 eCornell. All rights reserved. All other copyrights, trademarks, trade names, and logos are the sole property of their respective owners.
Python Fundamentals
Cornell Computing and Information Science
In this video, you will follow an example from Professor White and
practice visualizing assignment statements. Be sure to have a pencil and
paper before you start, as you'll need to use both.
Video Transcript
In this video, we're going to build your visualization skills. In a previous
video on creating variables, we introduced the concept of an assignment
statement, and we pointed out how, when Python processes assignment
statements, it does it invisibly. However, our graphic designers were able
to show you what was happening behind the scenes, and that helps you
understand what was going on with assignment statements.
Unfortunately, you're not always going to have our graphic designers at
your disposal, and we want you to be able to do this by yourself. So this
video and the next are going to have a slightly different format. We're not
going to be typing any Python this time. Instead what we're going to do is
we're just going to give you some assignment statements, and we want
you to guess what our graphic designers are going to draw. Now, to do
this, you should probably follow along on a piece of paper, and you
probably want to pause every now and then to give yourself a chance to
think about what's going on. But in this video, we're just going to work
through one example, going through all the details so that you
understand how this visualization works. And in the next video, we're
going to have a much deeper dive with several examples. Finally, after
both of the videos, we'll have an assessment to make sure that you've
understood everything that you've done.
© 2019 eCornell. All rights reserved. All other copyrights, trademarks, trade names, and logos are the sole property of their respective owners.
Python Fundamentals
Cornell Computing and Information Science
x+2". Remember that assignment statements are read right to left. So the
very first thing that you should do is evaluate the expression "x+2". In this
case, the value for x will be what is inside of the box, which is 5. So take
x plus 2 and compute a value. Once you have the value, we want you to
store that value in the variable x. So cross off the old value in the box and
write the new value in a box for x. At this point, pause the video; if you
need more time, we'll wait. OK; so let's see what you have. Does your
picture look like this? Do you have a box x which has a 7 in it, which is
below the original box x which has a 5 in it? Well, that's probably not right
because, remember, we said something about crossing off. So, maybe
you have two boxes like this; a box which has a 5 in it but it's crossed off,
and another box which has a 7 in it. Or perhaps you did it differently. You
have a box x which has a 5 in it crossed off, and then to the side of it you
have a 7. Well, the last picture is correct in the sense that this is what we
want. And this whole process that we've just done here is what we call
executing the assignment.
Now why are all these details important? Remember that visualization is
a metaphor. It's helping us to understand Python's workings, and the box
is really a metaphor of a memory location. So let's think about what these
other two pictures claim. If you're saying that every time that I do an
assignment statement I have to make a new box for x, you're saying that
each assignment statement needs a new memory location, and either the
old value is still hanging around in memory, or you're claiming that it's
been crossed off and it can't be reused. And if this were true, this would
mean that we'd be running out of memory. So — and that's not true,
right? Assignment statements reuse a memory location. And that's the
reason why this particular visualization is important in our metaphor. The
other thing to understand is that crossing off is a very helpful mental
model. It emphasizes that the old value was deleted. But also it shouldn't
stay there over time, else we might think that a box remembers its old
values. So what do we do? Well, when we execute the assignment
statement, we do cross it off at that time, but then later on, when we want
to talk about the variable again, we're not going to have that crossed off
there anymore. All of this is part of our visualization. So, now that we
have this laid out, in the next video, we're going to work through several
examples.
© 2019 eCornell. All rights reserved. All other copyrights, trademarks, trade names, and logos are the sole property of their respective owners.
Python Fundamentals
Cornell Computing and Information Science
Video Transcript
OK; so now what did you draw? Now, once again, you probably
remember that we're only going to have a single variable x; we're not
going to draw multiple boxes. So what we've done is we've taken our box
x that has a 7 in it, and we've crossed off the 7, and you probably put a
22 there, right? Well, did you just put 22 there, or did you put 22.0?
Because remember, there's a difference; 22 is an int and 22.0 is a float.
And remember that when we multiply an int — which is what x was to
begin with — by a float, the answer that we get is a float. And it's always
important for us to keep track of what types we're dealing with. Another
thing to take away from this is that variables can change types. At one
time we might have an int inside of x, then we might change our mind
and we might want to put a float inside of there instead. OK; so let's build
off of this. So now we have, once again, our variable x which has 22.0
inside of it; we can forget the 7 at this point. Now what we're going to do
is we're going to add another variable "interestRate" with the value 4.
Now, "interestRate", notice, it's a long word; it even has some
capitalization in the middle, But that's perfectly fine, right? Variables don't
have to be a single letter. We've talked about how Python recognizes
variables like this. And now what I want you to do is to execute the
© 2019 eCornell. All rights reserved. All other copyrights, trademarks, trade names, and logos are the sole property of their respective owners.
Python Fundamentals
Cornell Computing and Information Science
So now what do you have? Well, you should definitely have the two
variables, x and interestRate, which were originally 22.0 and 4, and you
have to do some crossing off. So what did you do? Did you cross them
both off and make them both 5.5? Or did you just cross off interestRate
and make it 5.5? The second answer is the one that is correct. Because
even though this assignment statement involves two variables, both x
and interestRate, it is only the variable on the left-hand side of the
assignment statement that changes. All right. So as one last example, we
now have this; we have x, which has 22.0 in it, and we have interestRate,
which has 5.5 in it. And now what we want you to do is to execute this
assignment statement: "intrestRate = x + interestRate". Look very
carefully on the screen as to how we have written this assignment
statement before executing it. Once again, pause the video if you need
more time; we will wait.
All right. So what do you have? At this point, you've probably figured it
out, right? We have the variable x, which has 22.0 in it; that hasn't
changed. And interestRate, right; you crossed off the 5.5, and now you've
made it 27.5. Except that's not the right answer. Because if you paid
attention to the assignment statement, you will notice that we actually
misspelled the word "interestRate" in the assignment. And what has
happened is, since we misspelled it, Python has created a second
variable, which is "intrestRate". And that has the 27.5 in it, but the
interestRate still has a 5.5 in it. I was being a little tricky here, but what
I'm pointing out is that spelling mistakes in Python are very bad, because
Python will do what you say, not what you mean. This also creates a
rather interesting trade-off about variables. Sometimes people like to
have just single letters as their variables because you're less likely to
misspell them. However, when we start to write more interesting code,
you'll discover that people like to have descriptive variable names; it's a
lot easier to write your code when you do that. But if you decide to have
more descriptive variable names, you might need to run a spellchecker
on your code, because, as we can see, typos can add extra variables.
© 2019 eCornell. All rights reserved. All other copyrights, trademarks, trade names, and logos are the sole property of their respective owners.
Python Fundamentals
Cornell Computing and Information Science
© 2019 eCornell. All rights reserved. All other copyrights, trademarks, trade names, and logos are the sole property of their respective owners.
Python Fundamentals
Cornell Computing and Information Science
© 2019 eCornell. All rights reserved. All other copyrights, trademarks, trade names, and logos are the sole property of their respective owners.
Python Fundamentals
Cornell Computing and Information Science
Video Transcript
In this video, we're going to return to the string type that we talked about
in the previous module on expressions. And indeed, this video is going to
seem a little bit out of place in this module because we're just going to be
talking about more expressions with strings. But we're also going to be
talking about variables, because the thing about string expressions is
they can get pretty complicated and sometimes they can be hard to write
on one line. This is a great application for variables. What we're going to
see is that variables are going to allow us to take a complicated
expression and make it simpler by breaking it up over multiple lines. To
understand what I'm talking about here, let's dig a little deeper with
strings. So I'm going to start by making the string 'abc d'. And remember,
when we type a string into Python, we have to do it in between two
quotes. I've typed the expression, and Python has given me the value.
I'm now going to do this as an assignment statement; I'm going to assign
this to the string s. I look at this s as a variable, and inside of that box, I
have 'abc d'. But remember, what Python actually does with strings is it's
not just in this case putting it in a single box, but it's breaking it up into a
bunch of little boxes. So there's a box for a, a box for b, a box for c, a box
for the space, and a box for d. In addition, Python gives each of these
boxes a number, and that number is indicating the position of that
character in the string. So a is the first character of that string. Python is
going to give it a number. In this case, it's not going to give it the number
1; it's going to give it the number 0. Because in Python, strings begin at
0, and indeed that's true for most programming languages. 1 instead is
going to be the position for b, 2 is the position for c, 3 is the position for
the space, and 4 is the position for d.
© 2019 eCornell. All rights reserved. All other copyrights, trademarks, trade names, and logos are the sole property of their respective owners.
Python Fundamentals
Cornell Computing and Information Science
Now, why is this useful? Because there are some new expressions that I
can write where I'm accessing the individual characters of a string. The
way I do that is, in this case, I'm going to take the variable s and I'll write
a square bracket. And inside of the square bracket, I'm going to give it
the position that I want to access, and then I close with a square bracket.
I'm going to type this into Python. Python recognizes this as an
expression, and it gives me back a value; in this case, it gives me back
the string 'a'. What it's done here is it's taken the string with five boxes in
it and it's given me the first box, the one at position 0, as its own string. If
I were to redo this and I put 1 inside of the square brackets, I would just
get the box for 'b'; 2, I get the box for 'c'; 3, I get the box for the space;
and 4, I get the box for d. If I were to put a 5 here, you'll notice that we
get an error, and that's because there is no box for 5. OK; so I can
access individual characters, but I can also access a range of characters
as well. And the expression is very, very similar. Again, I'm going to type
in s, the square brackets, and I'm going to type a 1 because that's where
I want to start. But now I'm going to type a colon. And I'm going to to tell
Python, "I don't want just one character; I want to go all the way up to
position 3." And once again, I close it with a square bracket. I hit Return,
and now you'll notice that I get the string bc, and that's because b is at
position 1 and c is at position 2. You'll notice that I don't get the space,
and that's because when I tell Python that I want from 1 to 3, it's up to but
not including the 3, and so therefore it doesn't include the space. If I
wanted to include this space, I would have to rewrite this as "s[1:4]". So
now, I have 'bc' and a space; b at position 1, c at position 2, the space at
position 3, and — well, I'm not including the 4. So what we've noticed
here is that what I can do is I can take a long string and I can write
expressions that cut it up into little strings. And this is what is known as
string slicing.
Now, when we did this, we made heavy use of the variable s, because
that was what stored our string. But there's nothing special about that. I
could have typed the string 'abc d", and then after the string with the
quotes, I could have typed the square brackets and accessed the
individual characters. The advantage of typing it as s is, well, number
one, it just allowed me to type things a lot faster; I didn't have to keep
typing the string each time. But it also made the expressions a lot shorter.
This is not the only place where I could use a variable; I could also use a
variable inside of the square brackets as well. So I could make a variable
© 2019 eCornell. All rights reserved. All other copyrights, trademarks, trade names, and logos are the sole property of their respective owners.
Python Fundamentals
Cornell Computing and Information Science
© 2019 eCornell. All rights reserved. All other copyrights, trademarks, trade names, and logos are the sole property of their respective owners.
Python Fundamentals
Cornell Computing and Information Science
Video Transcript
Now this might seem really unusual because actually if I tried to access
the individual character at 5, you'll notice that I get an error, and that's
because there is nothing at position 5. When you use the colon notation,
Python is very forgiving about what you say. So not only could I say "
[1:5]", I could also say "[1:10]", and Python knows that, "OK; well, there is
nothing after position 4, but you're just telling me to go all the way to the
end of the string." In fact, I could even do the following: If I just want to go
to the end of the string, I could just type the colon, and I don't have to
type anything after that. Python knows, "Oh, you want to start at position
1, which is the e, and you want to go all the way to the end of the string."
The reverse is true. Suppose I wanted to start at the beginning of the
string but I wanted to go to the position 3. In this case, I don't have to
type anything before the colon; I just have to type the 3 afterwards. And
Python knows to start from the beginning. And in fact, you can even do "
[:]", and now Python knows that you want the whole string. That's one
© 2019 eCornell. All rights reserved. All other copyrights, trademarks, trade names, and logos are the sole property of their respective owners.
Python Fundamentals
Cornell Computing and Information Science
shortcut. The other useful shortcut is that Python will allow you to put
negative numbers inside of the square brackets. So I type an s, a square
bracket, and a negative 1. Now, there is no position negative 1, right?
There's only positions 0, 1, 2, 3, and 4. But if I type a negative 1, or a
negative number, what Python does is it works backwards from the right.
So negative 1 is actually position 4. Negative 2 is position 3, negative 3 is
position 2, negative 4 is position 1, negative 5 is position 0. And now if I
do a negative 6, now I get an error because I've gone too far. Putting all
of these things together, I could now do something like slice from position
1 but up to negative 1. And this is a very quick way of telling Python I
want to go from position 1, which is the second character, up to but not
including negative 1, which is the last character. And what happens in
that case is Python cuts off the two ends of the string.
© 2019 eCornell. All rights reserved. All other copyrights, trademarks, trade names, and logos are the sole property of their respective owners.
Python Fundamentals
Cornell Computing and Information Science
Slicing Strings
This terminal is to assist you as needed. See below for instructions.
© 2019 eCornell. All rights reserved. All other copyrights, trademarks, trade names, and logos are the sole property of their respective owners.
Python Fundamentals
Cornell Computing and Information Science
© 2019 eCornell. All rights reserved. All other copyrights, trademarks, trade names, and logos are the sole property of their respective owners.
Python Fundamentals
Cornell Computing and Information Science
© 2019 eCornell. All rights reserved. All other copyrights, trademarks, trade names, and logos are the sole property of their respective owners.
Python Fundamentals
Cornell Computing and Information Science
© 2019 eCornell. All rights reserved. All other copyrights, trademarks, trade names, and logos are the sole property of their respective owners.
Python Fundamentals
Cornell Computing and Information Science
© 2019 eCornell. All rights reserved. All other copyrights, trademarks, trade names, and logos are the sole property of their respective owners.
Python Fundamentals
Cornell Computing and Information Science
In this video, Professor White introduces you to functions that are built
into Python and how to access these functions. Further information on
built-in functions is available on the Python documentation website.
In this video, Professor White focuses on two functions and shows how
they are valuable tools for text and string processing.
Video Transcript
For a function that might take more than one argument, let's look at
finding the maximum of two numbers. So in this case, the name of the
© 2019 eCornell. All rights reserved. All other copyrights, trademarks, trade names, and logos are the sole property of their respective owners.
Python Fundamentals
Cornell Computing and Information Science
There are bunch of functions that are built into Python and you've seen
several of these already. Back when we were talking about types, we
showed how to convert from one type to another. For example, if I
wanted to convert an int to a float, I would type the name "float" and then
inside of these parentheses I would type the integer that I want to convert
to a float; in this case, the number 2. I hit Return, and it becomes a 2.0.
This is an example of a function call. In this case, the name of the
function is the word "float." And I've given it parentheses, and inside of
that I've given it the argument to convert to float. Similarly, the function to
convert to ints or to bools, they work exactly the same way. There are
several functions that are built into Python and if you want to learn any
about them, well, we have a web page that's linked to on the Canvas site
that gives you an explanation of a lot of these functions. In front of me
right now is that I have a list of several of these functions. A lot of these
functions are a little too advanced for us right now, though it's still worth
looking over this and getting yourself familiarized with the types of
functions that are in Python. But we're just going to focus on two very
specific functions. In particular, these functions that we want to focus on
are different than functions like round or maximum. Both of those
functions are examples of expressions. So when I typed "round (2.34)",
that's an expression. Now I hit Return; Python gave me a value back.
Also, because it's an expression, I could use it inside of an assignment
statement. So I could assign x to be equal to a round of 2.34, and now
what this has done is this has put the number 2 inside of x. However,
there are two other functions; in this case, they are help() and quit(),
which are slightly different because they're not expressions. When I call
© 2019 eCornell. All rights reserved. All other copyrights, trademarks, trade names, and logos are the sole property of their respective owners.
Python Fundamentals
Cornell Computing and Information Science
them, Python doesn't actually create a value, and it's not something that I
can assign to a variable. Instead, in this case, the functions themselves
are commands that tell Python to do something.
For example, let's go look at help(). Help() is a very simple function. I'm
going to type its name, but this is important: I can't just type "help" by
itself. If I do that, Python doesn't understand what I'm talking about. Every
single function call has to have parentheses after it, even though in this
case help() doesn't have any arguments. But the parentheses are
important for Python to know that this is a function call. I'm going to hit
Return, and now what you'll notice is this is not an expression; I didn't get
a value. Instead, Python has dropped me into this help menu. In fact, if I
tried to type in an expression for Python to evaluate it, like "1+1", you'll
notice that Python doesn't know what I'm talking about. But I can do
things like, "Hey, tell me some topics that you can give me help on." This
lists a bunch of things that Python can help me with. And if at any time
I've decided that I'm done with the help menu, I just type the word "quit,"
and now I'm back to normal Python and I can type expressions once
again. Finally, the other important command is quit(). Let's suppose we
want to leave Python. Well, you would think, "I'll just type 'quit' by itself,"
but once again, you can't do that; Python is expecting a function, and the
function call must have a parentheses after that. So now I type the word
"quit" with parentheses, I hit Return, and now you'll notice that I've left
Python altogether; I'm now actually in the normal Terminal where I can
look at files. If I were to type "1+1", Python wouldn't know — well, in fact,
the Terminal wouldn't know what I'm talking about here because I'm not
running Python. If I want to be able to do that expression again, I have to
start Python all over again, and now I can add 1 plus 1. So this is a really
interesting question, right? Some functions are expressions, and then
other functions are commands; how can you tell which is which? Well,
that is indeed the purpose of the documentation that we've linked to on
the Canvas page.
Video Transcript
these two functions are going to show the important difference between
using a function as an expression or using a function as a command.
Now, in each of these examples, we're going to be working with strings,
so the first thing that I'm going to do is I'm going to create a string — in
this case, 'Hello' — and I'm going to assign it to the variable s. Now I'm
going to use my first function, which is len(), for computing the length of a
string. To call this function I type its name, and I type the name l-e-n. It's
not "length"; it's "len". Python likes to use abbreviations for its function
names. Now, I'm going to type parentheses, and inside of the
parentheses I'm going to give it the variable s, which has my string in it.
I'm going to hit Return, and now you'll notice that it has evaluated to 5,
and that's because there are five characters in the string. I could call this
function again with — instead of using a variable I could put a straight
string in it like 'abc'. Now I'm going to hit Return, and you're going to see
that it's going to give me the number 3, and that's because there are
three characters in the string. Now this is an expression, which means
that I can mix and match it with other expressions.
So, for example, I could do len(), and inside of it, instead of just looking at
s, I could actually slice s from 1 to 4. This time you'll notice that I get the
answer of 3. And to just verify that is indeed the right answer, if you just
look at that slice of that string, you'll notice that that is actually the letters
e and l. More importantly, I can actually use this function inside of string
slices. So I could say, all right, I'm going to take the string s and I want to
slice it from 1 and I want to go all the way up to the length of the string
minus 1. What this has done is, well, it starts at position 1, which is e,
because strings start at 0, and it goes up to but not including the last
position of the string. So this has the effect of slicing off the two ends of
the string. That's one function. The other function that we want to look at
today is print(). Print() is used as a command, and what it does is it
displays whatever string that you've given it on screen. So now I'm going
to print(s). And notice that it gives me "Hello", and this looks like — well,
OK, this is a function that's an expression and it gives me back a value.
But it's important to understand that that "Hello" is not actually a value.
And how do I know? Well, if I type the word "Hello", Python is confused.
Remember, that in order to give a string to Python, I have to remember to
put it between two quotes. So what print() does is it removes the quotes
from the string when it displays it on the screen. That's one way that you
can tell that, OK, this is not actually an expression. Another way that you
© 2019 eCornell. All rights reserved. All other copyrights, trademarks, trade names, and logos are the sole property of their respective owners.
Python Fundamentals
Cornell Computing and Information Science
© 2019 eCornell. All rights reserved. All other copyrights, trademarks, trade names, and logos are the sole property of their respective owners.
Python Fundamentals
Cornell Computing and Information Science
© 2019 eCornell. All rights reserved. All other copyrights, trademarks, trade names, and logos are the sole property of their respective owners.
Python Fundamentals
Cornell Computing and Information Science
In this video, Professor White shows you how to add further functionality
to Python through the use of modules.
Note: These are entirely separate from the modules of this course. To
prevent ambiguity, a course module refers to a module in Canvas, while
a Python module refers to a file that can be imported in Python.
Video Transcript
In a previous video, we talked about the functions that are built into
Python, and we even gave you a link to a web page that listed these
built-in functions. If you'd looked at that web page, you notice that that list
is pretty small and that there are a bunch of functions that you would
expect Python to have that weren't there. For example, sine() and
cosine(), right? These are pretty standard functions and they're not listed
on that page. And that's because they aren't built into Python, right? If we
pull up Python and we tried to call cosine(), it's not going to work. Let's
just do it like we would do a normal function call. We type the name,
which is cosine(0). You notice we got to get an error message; Python
doesn't know what I'm talking about. OK; well, maybe you realize that
Python likes to have abbreviations. So let's type "cos" by itself, then
parentheses and a 0, and see if that works. Well, that doesn't work either,
and that's because Python doesn't know what we're talking about when
we want cosine. But that would seem really strange, right? I mean, most
programming languages should be able to do the types of things that you
can do on a normal calculator. That's because while sine and cosine
aren't built into Python, they are provided by modules. So modules are
files that contain Python code, and they're a way that Python can provide
© 2019 eCornell. All rights reserved. All other copyrights, trademarks, trade names, and logos are the sole property of their respective owners.
Python Fundamentals
Cornell Computing and Information Science
To import a module, I just type the word "import" first, and then a space,
and then the name of the module that I want to import. In this case, the
name of the module that I want is "math," which contains a lot of math
functionality. I'm going to hit Return, and you'll notice that I don't get an
error message, right? So obviously I must have done something right
here. OK; well, so now maybe we have cosine. So let's type "cos(0)".
Again, I get an error; Python doesn't know what I'm talking about. That's
because it's not enough to import the module. When you want to access
a function that is provided by the module, you have to call it in a very
special way. You can't type the name of the function first; instead, you
have to type the name of the module first. This case, my module is math,
so I type that first, then I follow it by a period, then the name of the
function, which in this case is cos(0). And now I don't have an error
message. The cosine of zero is indeed 1, right? This is the math module;
it provides a lot of basic math functionality. It's also where sine lives. If I
want to call sine(), once again, I type the name of the module, which is
"math", then "sin(0)". And sine of zero is zero. In addition to functions,
modules can also contain variables as well. Let's suppose you don't quite
remember what the value of pi is. Well, instead of having to type it by
yourself, what you can do is you can access the variable pi inside of the
module math. To do that, once again, you type the name of the module,
which is math, then a period, then "pi". We're not going to give a
parentheses this time because it's not a function; instead, it's a variable. I
hit Return, and you'll notice that I now have the value at least to some
approximation of pi, and I can mix and match these together. So
"math.cos(math.pi)", well, that's cosine of pi, which is negative 1. There
are a lot of modules that are built into Python. And in fact, on the Canvas
page, we've given you a link to the page that lists a lot of these modules.
In fact, I have this page on the screen here, and you'll notice that it lists
"math," which we've just looked at. A lot of these modules are a little too
advanced for us, but one more module that I'd like to look at which is
going to be important throughout the next module is the module known
as "random," which is used to generate random numbers. Let's import
that module. I've imported "random." Inside of "random" is a function
called "randint"; "random.randint". And what it does is I give it two
© 2019 eCornell. All rights reserved. All other copyrights, trademarks, trade names, and logos are the sole property of their respective owners.
Python Fundamentals
Cornell Computing and Information Science
© 2019 eCornell. All rights reserved. All other copyrights, trademarks, trade names, and logos are the sole property of their respective owners.
Python Fundamentals
Cornell Computing and Information Science
© 2019 eCornell. All rights reserved. All other copyrights, trademarks, trade names, and logos are the sole property of their respective owners.
Python Fundamentals
Cornell Computing and Information Science
Video Transcript
Now, you'll notice that when it lists each of these functions, it lists them in
a very important way. The first thing that it does is it puts the word
"math," and that's to remind ourselves that when we use this, it's part of
© 2019 eCornell. All rights reserved. All other copyrights, trademarks, trade names, and logos are the sole property of their respective owners.
Python Fundamentals
Cornell Computing and Information Science
the math module, and so we have to type the word "math" first. Then we
have the name of the function, then we have a set of parentheses, and
now you'll notice that inside of the parentheses, it has a variable. Now,
this variable doesn't mean that you should type the letter x in there; it just
means that it's expecting something inside of the parentheses, and in this
case, x is just being used as a placeholder. So if I were to try square root,
I would type the name "math" first, then "sqrt", parentheses, and instead
of typing x, I'll just put in here whatever I want to compute the square root
of; in this case, 2. Another important thing that you'll notice about the
documentation is underneath the name of the function is a paragraph
which tells me what the function does. In this case, if I'm looking at the
documentation for square root, it tells me that it returns the square root of
x. And indeed, this is the reason why it was using x as a placeholder,
because it's important for me to have that information to know how to use
the function. Let's look at another interesting function here, which is
"power." So "power" is used to raise one thing to another; say x to the
power of y. Now, you'll notice in the documentation, once again, it lists
"math", then it lists a period, then the name of the function, which is
pow(), but now inside of the parentheses it lists an x and a y. Here, the
documentation is telling me that this particular function must have two
arguments. In particular, if I were to try to call "power" with just one
argument, you'll notice that I get an error message, and the error
message is a very helpful "It expected two arguments, but it only got
one." So if I want to take 2, and I want to raise it to the power of 2, I've
now done it with two arguments, and you'll notice that I have a 4.0. Let's
scroll up to one more interesting function, which is log(), for finding the
logarithm. There's a very interesting thing if you'll notice about this
documentation. It lists two arguments; it lists an x and a base. But you'll
notice the base is inside of square brackets.
What this means is that base is actually an optional argument. It's not
required. So when you call "logarithm", you can call "logarithm" with only
one argument, or with two arguments. So if I were to call, say, math.log()
by itself, on 1, well, you get an answer of 0. On the other hand, if I call it
with, say, 10, you might expect that I get 1, because normally you might
have learned that the log of 10 is 1. But I actually get a slightly different
answer here, and that's because, well, it's not log(10). In fact, if we read
the documentation, we'll notice that, oh, actually it's the logarithm to base
e. So, in fact, if we looked at the log(math.e), which is a variable inside of
© 2019 eCornell. All rights reserved. All other copyrights, trademarks, trade names, and logos are the sole property of their respective owners.
Python Fundamentals
Cornell Computing and Information Science
"math", now we'll notice that we have the value of 1. If instead we wanted
to use log(10), which is maybe a little more comfortable for us, then we
have to use the second argument. So it would say 10, comma, 10 as our
base, and now we would get the answer of 1. All of this is well and good,
right? And at all times I can be using the web page to help me learn more
about "math." And in fact, if you scroll through this, you should be able to
understand most of the functions that are in "math." However, sometimes
you may not have the web page handy. If that's true, you can use the
help() function to help you. We've seen the help() function before, but
when we've called it, we called it with parentheses and nothing inside of
it. But what you can actually do is, in addition to that, you can put the
name of a module inside of these parentheses. Now, when we hit Return,
you'll notice that I get some information, and if I keep hitting space, what
you'll notice is that it looks very, very similar to what we see on the web
page. It's essentially the same information, but now I have it available to
me in the Terminal, and I don't have to go to the web page.
© 2019 eCornell. All rights reserved. All other copyrights, trademarks, trade names, and logos are the sole property of their respective owners.
Python Fundamentals
Cornell Computing and Information Science
© 2019 eCornell. All rights reserved. All other copyrights, trademarks, trade names, and logos are the sole property of their respective owners.
Python Fundamentals
Cornell Computing and Information Science
© 2019 eCornell. All rights reserved. All other copyrights, trademarks, trade names, and logos are the sole property of their respective owners.
Python Fundamentals
Cornell Computing and Information Science
In this video, Professor White shows how to access string functions and
demonstrates examples of these.
Video Transcript
Now that we know how to use module-based functions, let's look at some
more interesting examples. Once again, we're going to use strings, or
text, as sort of our example. Now, most of the features that Python
provides for strings are actually done not through function but what are
called methods. Methods are an advanced feature that are far beyond
the scope of this course. You could look them up online, but they're not
really suitable for beginners. And we want beginners to work with strings
because text processing is one of the things that Python is really known
for. The solution is the IntroCS module. This was a Python module which
was installed in the first course module, all the way back at the beginning.
Now, this module provides many, many string functions, and they are
provided in such a way that they're easy for a beginner to use. Let's look
at some examples. Let's start off and let's make a string. So I'll make a
string s. And I'm going to start with a lot of spaces, and type an 'a' and a
'b', and then a bunch of spaces, and then I'm going to end the string.
What I want to do is I want to strip the spaces away from this string. So to
do that in IntroCS, the first thing I have to do is import the module; "import
introcs". And now I'm going to call the function strip(). So I type the name
of the module first, a period, then the word "strip," and now I give it the
string that I want to strip. And what you've noticed is that it removes the
spaces at the beginning and end of the string. That's the only place
where it removes spaces. If I, say, have a different string, let's say x,
which is a bunch of spaces, 'a', a bunch of spaces, then a 'b', and then
finally a bunch of more spaces — if I call strip() on this particular string,
you'll notice that I removed the spaces at the beginning and the end but
none of the spaces in the middle. There are one-sided variations of this
function as well. There is lstrip(), which removes the spaces from
© 2019 eCornell. All rights reserved. All other copyrights, trademarks, trade names, and logos are the sole property of their respective owners.
Python Fundamentals
Cornell Computing and Information Science
Let's look at a function that takes multiple arguments. In this case, what I
want to do is I'm going to take a very simple string like 's = abbac'. And
the important thing to notice about the string is that some letters appear
once and some letters appear twice. So what I actually want to do in this
case is I want to count the number of times that each letter appears in the
string. So the way that I do that is with a function called count_str(). To
call the function, I would type the name of the module, which is
introcs.count_str(). And now I'm going to give it two arguments. The first
argument is the string that I want to do the counting with, which in this
case is the string s, and then I would follow that with the string that I
actually want to count. So if I want to count the number of times that 'a'
appears inside of the string in the variable s, I would type s first and then
'a', and you'll notice that when you hit Return, this evaluates to 2 because
'a' appears twice in that string. On the other hand, if I wanted to count the
number of times that 'c' appears inside of this string, I would change the
'a' to a 'c', and now I get value of 1. If I count the number of times 'x'
appears here, well, there is no 'x' in the string, so I get a value of zero.
When I'm doing counting, I'm not limited to single letters. This is very
similar to the in operation that we saw with strings. I could count how
many times 'ab' appears inside of here. And you'll notice it only appears
once, and that's because even though I have 'a' appears twice and 'b'
appears twice, together 'ab' only appears once in that order.
Video Transcript
One last, very useful function in this module is "index string," and this is
used to help us not just count where a string is located inside of one
another, but to determine where it is located. So let's look once again at
our string s, and now I'm going to type index_str(), I'm going to take s,
and I'm going to give it the letter 'a'. This time you'll notice that I get the
© 2019 eCornell. All rights reserved. All other copyrights, trademarks, trade names, and logos are the sole property of their respective owners.
Python Fundamentals
Cornell Computing and Information Science
value of zero. And it's not because there isn't any 'a' there; there are two
'a's there. It's just that the first time that 'a' appears in the string is at
position 0. And indeed if I were to look at position 0 in the string, I would
notice that it is the letter 'a'. Similarly, if I wanted to ask what is the index
of the letter 'c', you'll notice that I get the number 4. And if I look at
position 4 of the string, you'll notice that indeed it is the value 'c'. On the
other hand, let's suppose I wanted to search for something that doesn't
exist, like the letter 'x'. If I do that, you'll notice that actually Python
crashes. Index string only works properly if the thing that you're
searching for is inside of the string. That may seem really weird, but
that's sort of a design decision that Python has chosen; it's a bit beyond
the scope of this course. If you're uncomfortable with that, there is a
variation of index string called "find string." So if I just change the name
"index" to "find," now it won't crash; instead it actually gives me the
number negative 1 to indicate that nothing was actually found at all.
Which one you would like to use, index or find, is largely a matter of
preference. Finally, for index string, just like count, you aren't limited to a
single letter. If I wanted to search for 'ab' inside of the string, you'll notice
that I have the position 0. If I wanted to look at 'ba', you'll notice that I
have the position 2. What's happening in here is that when I search for
'ab' or 'ba', even though I'm searching for two characters, it will tell me the
position where that string starts. So the 'ab' starts at position 0, but 'ba', if
I take s and I slice it from position 2, you will notice that 2 is where 'ba'
starts inside of the string. There are a lot of things that are provided to us
by this IntroCS module. But it's not an official part of Python and you can't
actually learn about it from the main Python web page. And that's
because it was a module created here at Cornell for students, and this is
one of the reasons why we had you install it. But we have actually made
documentation for you, and this documentation is available from the
Canvas page. If you look at it, you will notice on this web page that
IntroCS actually provides a lot of functionality, but in this course we're
only going to be using the string functions. So if you click onto the "string
functions" link, you will notice that the format is very, very similar to the
documentation that we saw for "math," and you can now read through all
of these functions and learn how to use them to process strings.
© 2019 eCornell. All rights reserved. All other copyrights, trademarks, trade names, and logos are the sole property of their respective owners.
Python Fundamentals
Cornell Computing and Information Science
© 2019 eCornell. All rights reserved. All other copyrights, trademarks, trade names, and logos are the sole property of their respective owners.
Python Fundamentals
Cornell Computing and Information Science
© 2019 eCornell. All rights reserved. All other copyrights, trademarks, trade names, and logos are the sole property of their respective owners.
Python Fundamentals
Cornell Computing and Information Science
Video Transcript
One of the annoying things about using module-based functions is
whenever you want to call the functions, you have to type the name of
the module first. So, for example, right, when I import the module "math,"
if I wanted to access the variable cosine, I can't access cosine by itself;
that gives me an error. I have to type "math.cos" first. Now, as a result,
we find ourselves typing "math." a lot, and this can actually get really
annoying. There is a way to actually import things so that I don't have to
remember to type the module name each time, and that is done using the
word "from." So instead of typing "import" first, I'm now going to type
"from", and then I'm going to use that to give me the name of the module,
which is "math." And now instead of importing the module, I'm going to
import the specific function. So from "math," I'm going to import cosine.
Now I can actually type "cosine" by itself, and that's because I've told
Python I'm not importing a module; I'm importing a specific function.
However, this means that I only have access to cosine this way, right?
Inside of "math", I have access to the variable pi, and we saw that we
could use math.cos(math.pi). So you go, "OK, well, now that I've
imported cosine by itself, can I just type cos(pi)?" Well, I can't actually do
that. That's because while I imported cosine by itself, I have not imported
pi. Well, OK, once again, this is something that we can solve. What we
do is we type "from math import", and now we say, "I want to import
everything," and we tell it *. Now what we've done is we've told Python,
"Import every single function and variable inside of 'math' in such a way
that I don't actually have to type 'math.' first." So I can type cos(0), I can
type sin(0), I can even type cos(pi). There's no need for us to type
"math." in front of everything else.
© 2019 eCornell. All rights reserved. All other copyrights, trademarks, trade names, and logos are the sole property of their respective owners.
Python Fundamentals
Cornell Computing and Information Science
Now, this seems great; it seems like we probably should have done this
all along. But you need to be very careful when using "from". And the
reason why is because "import" is slightly safer, because what happens
is that modules can conflict with one another. You can have modules that
have functions of the same name. This might seem a little weird, but
there's a very simple example. There's a module called NumPy. I'm going
to "import numpy". and NumPy, like "math", is used for scientific
calculations. In particular, NumPy has its own value of the variable pi and
it has its own version of the function cosine(). This may seem really
weird, right? Why does Python have two different modules for supporting
sine, cosine, and pi? This is actually a performance reason. NumPy is
used for scientific calculation, so its functions are a lot more powerful and
a lot faster. But NumPy isn't available on all systems because it requires
certain things in order for it to work properly. Whereas, on the other hand,
"math" is always available in a Python installation. So what Python has
done is, the reason why it puts cosine and sine into extra modules is
because it's allowing you to choose whether or not you do math or
whether or not you do NumPy. Unfortunately, if we use the "from" syntax;
say, "from numpy import * ", now I no longer have any control over which
one am I using? Because if I type "cosine" by itself, which one am I
using? Am I using the NumPy version or am I using the "math" version?
Actually, in this case, I'm using the NumPy version because it's the last
one that I imported. But in general, this can be confusing and this is
something that should be avoided. Another interesting thing that we can
do with importing is you can actually rename a module. So I could import
"math", but I could say, "Actually, what I want to do is I want to rename it
to m because I just want to cut down on the number of things that I want
to type." So I do that by typing "import math as m", and now what's
happened is instead of typing math.cosine, I can type m.cosine. I can
type m.sine, or I can look at m.pi. So this is safer than using the "from"
syntax, but it gives me a way of cutting down on the number of things that
I have to type. I can also do things like rename functions; "from math
import cos as fred". And now I have a function called fred() which
behaves exactly like cosine().
In this video, Professor White uses IntroCS to show that modules can be
within other modules, and how to access their functions.
Video Transcript
© 2019 eCornell. All rights reserved. All other copyrights, trademarks, trade names, and logos are the sole property of their respective owners.
Python Fundamentals
Cornell Computing and Information Science
One last feature with the concept of importing modules is the idea of
nested modules. Sometimes you have modules that are actually nested
inside of one another. And actually, IntroCS is an example of such a
module. If you look at the documentation page for IntroCS, you'll notice
that underneath "Contents," we have several links. There are the string
functions, but then there are a bunch of other functions that are sort of
beyond the scope of this course. When you import IntroCS, it actually
imports all of the things underneath "Contents," even though we don't
necessarily use all of them. Suppose we just wanted to use the string
functions by themselves. The way we would do that is we would "import
introcs", but we wouldn't just "import introcs"; inside of IntroCS, which we
would indicate with the period, we would import strings. So what we've
just done is we've told Python to import only the strings portion of
IntroCS. And this is where we might have a function like, say, strip();
"introcs.strings.strip", when we want to strip away the spaces from 'ab',
and we get the result. That's a lot to type now, right? Because now I have
to type "introcs.strings.strip". We can solve part of this problem with the
"from" syntax. we can say "from introcs", I want to import just the strings
portion of IntroCS, and now from strings. I call strip(), which is the
function, 'ab', strip away the spaces, and that does it. And finally, I could
just import the function by itself. So from "introcs.strings", I can "import
strip", and now I can call strip() by itself and that has the end result.
© 2019 eCornell. All rights reserved. All other copyrights, trademarks, trade names, and logos are the sole property of their respective owners.
Python Fundamentals
Cornell Computing and Information Science
© 2019 eCornell. All rights reserved. All other copyrights, trademarks, trade names, and logos are the sole property of their respective owners.
Python Fundamentals
Cornell Computing and Information Science
© 2019 eCornell. All rights reserved. All other copyrights, trademarks, trade names, and logos are the sole property of their respective owners.
Python Fundamentals
Cornell Computing and Information Science
Stay Connected
© 2019 eCornell. All rights reserved. All other copyrights, trademarks, trade names, and logos are the sole property of their respective owners.
Python Fundamentals
Cornell Computing and Information Science
The videos in this module work with several pre-made Python files. You
should download the file module5.zip if you're interested in looking at
these files when watching the videos.
© 2019 eCornell. All rights reserved. All other copyrights, trademarks, trade names, and logos are the sole property of their respective owners.
Python Fundamentals
Cornell Computing and Information Science
© 2019 eCornell. All rights reserved. All other copyrights, trademarks, trade names, and logos are the sole property of their respective owners.
Python Fundamentals
Cornell Computing and Information Science
In this video, Professor White uses the new Sandbox to demonstrate how
to import custom module files and explains a key rule of importing that
students often miss.
Video Transcript
In previous course modules, we used Python as a calculator, and that
meant we only needed to use the interactive shell, where you typed in a
Python expression and Python gave you an answer back. And that's
because interactive shell is very easy to follow along on your computer.
This meant that there wasn't really any need for Codio, which we actually
introduced in the first course module. But in this course module, we're
going to get a little more advanced. In particular, we're going to learn how
to work with Python files. That's going to require us to actually install
some more software, but first what we're going to do is start in Codio to
give us the big picture. We're also going to be using Codio much, much
more heavily for assessment during this course module. Now, this means
right away that we have a new Sandbox provided for you in this course
module. This is just like the Sandboxes that we had before; it's a place
for you to play, and you're not being assessed in this Codio Sandbox. But
you'll notice that in this case it has many files. You'll notice that we have
files for unit1, unit2, unit3, and so on. Actually, what's happening is, these
are all of the demo files for this particular course module. This is so that
you can follow along with what we are doing in the videos. If you would
prefer to work on your own computer and you don't want to work through
Codio, you can also download these files from the Canvas page. But a
more interesting question is, why do we have all of these files? And that's
because, well, the interactive shell is very limited.
Let's suppose we go to the Terminal and we start Python. And I'm going
to create a variable x and assign it equal to 1 plus 2. I'm going to change
the variable; I'm going to make it equal to 3 times x, so currently its value
© 2019 eCornell. All rights reserved. All other copyrights, trademarks, trade names, and logos are the sole property of their respective owners.
Python Fundamentals
Cornell Computing and Information Science
is 9. Now I'm going to quit Python, and I'm going to start Python again.
I'm going to ask, "What is the value of x?" And notice that I get an error.
That's because every single time that you quit and restart Python, all of
your work is lost. That's fine if all you want to be able to do is sort of do
one line at a time. But if you're writing more interesting Python programs,
it can be very frustrating for all of your work to be lost. So, how do we
save our work? Well, we do it just like we do anything else: We save it in
a file. And indeed, if we look at unit1 on this thing called module.py, we
double-click on it, we'll notice that what I have here is a file, and it's a file
with two assignment statements. What we're looking at here is sort of a
text editor, something that I can type text in, just like I might type in
Microsoft Word or in Notepad or whatever your text editor of choice is. A
more important question you might have is, OK, this is a file, but how do I
type? How do I get it to run Python? Because if I just type x, and hit
Return, well, this is just a text editor; it's not Python. Nothing actually
happens here. Well, let's remember what we did with scripts back in the
course module. What we would have to do is we would go into the
Terminal, and in this case I would have to quit Python first, and I would
need to navigate to the folder with that file. In that case, my folder is
unit1, so I'm going to use the "cd" command, and I'm going to change to
the folder unit1. If I type "ls", you'll notice that I see the file module.py. In
the first course module, we saw how to run this as a script. We type
"python", then the name of the file, "module.py". You'll notice it really
doesn't do anything, and that's because this is not actually a script, even
though it ends with a .py like those things that we saw in the first course
module. But we can use this like a Python module. And how would we do
that? Well, we're inside of the folder unit1, so what we can do is we can
start Python, and now we just "import module" and hit Return. Notice that
this worked properly and now the module is imported. In fact, actually, if
you look off to the left in the Filetree, you'll notice that Python has created
this mysterious folder called _pycache_. What's happened here is that
Python has read the file and has done some things behind the scenes to
sort of speed it up. But as you can tell, I've imported the module
successfully. Notice that when you import a module, you type the name
of the file without the .py. If I were to type "import module.py", Python
would know what we're actually talking about. So, how do I actually use
this module? Well, you use it just like you would use any other module:
You would access the functions or variables that are inside of that
module. Well, what are they? Well, why don't we just type help(module)?
© 2019 eCornell. All rights reserved. All other copyrights, trademarks, trade names, and logos are the sole property of their respective owners.
Python Fundamentals
Cornell Computing and Information Science
There's not a lot of help here, but you'll notice that, "Oh, wait; the help
menu tells me that there's a variable there, x, whose value is 9." OK; so,
once again, just like we've done before with variables, we type the name
of the module, which is "module", period, and then the name of the
variable that we want to access, which is x. There's one more important
thing to keep in mind when you're using these module files, and it's
something that often trips up students. You'll notice that we accessed the
module module.py, we were inside of the folder unit1. I started up
Python, and I imported module; it worked fine. And now let's quit. And
now what we're going to do is we're going to use "cd", and we're going to
back out. If we type "ls", we'll notice that we are no longer in the same
directory as module.py. If I start Python, and I try to "import module",
you'll notice that Python crashes. That's because it can't find the module
at all. You must always be in the same folder as the module file that you
want to access before you start Python. Once you have started Python,
it's too late for us to change; we have to quit Python and move back to
the folder to access it.
© 2019 eCornell. All rights reserved. All other copyrights, trademarks, trade names, and logos are the sole property of their respective owners.
Python Fundamentals
Cornell Computing and Information Science
© 2019 eCornell. All rights reserved. All other copyrights, trademarks, trade names, and logos are the sole property of their respective owners.
Python Fundamentals
Cornell Computing and Information Science
First, you should download module5.zip and put it anywhere you would
like. (We do not require you to use the Desktop this time.) You should
unzip the folder. On most MacOS and most Linux variants, you can do
this by double-clicking the file. On Windows, you will need to right-click
the file and select Extract All. This folder contains all the folders in the
Codio Sandbox for this module.
When you are done, take a screenshot of your command shell side by
side the graphical window for folder2. On MacOS, this will look something
like this:
© 2019 eCornell. All rights reserved. All other copyrights, trademarks, trade names, and logos are the sole property of their respective owners.
Python Fundamentals
Cornell Computing and Information Science
© 2019 eCornell. All rights reserved. All other copyrights, trademarks, trade names, and logos are the sole property of their respective owners.
Python Fundamentals
Cornell Computing and Information Science
Video Transcript
In the first course module, we showed you not just how to use Python
and Codio, but how to install and use it on your own computer. We did
this for several reasons. First of all, it's always important that you be able
to know how to use real-world tools. But also, you know, Codio goes
away at the end of the course, so you would like to have something to
show for all your efforts. But that means that you're going to need to have
something to edit code files. Well, this is just text, so you might go, "OK;
well, how about Microsoft Word?" But you don't want fonts or formatting;
you just want to deal with plain text. And in fact, with all that formatting,
Microsoft Word actually adds a lot of extra stuff there that would just
confuse Python. "OK; well, how about something simpler, like Notepad
on Windows or TextEdit on a Mac?" Those are better, and some people
do use those, but they're not really ideal for a beginner. For a beginner,
what we want is what is known as a code editor. This is a program that is
designed specifically to edit code.
Now, when I say "code," obviously that will include Python, but it can
support many other programming languages as well. These programs
can do some sort of simple error checking for you, and they'll also color
the text in ways that are going to be very useful to us later in the course.
Now, there are several popular code editors, but two of the most popular
are Atom Editor and VS Code. Personally, we prefer Atom Editor, and
© 2019 eCornell. All rights reserved. All other copyrights, trademarks, trade names, and logos are the sole property of their respective owners.
Python Fundamentals
Cornell Computing and Information Science
that's what we'll be using in our demonstrations in this course. One of the
reasons why we like Atom Editor is because it's very, very similar in its
visual style to Codio. Here I have pulled up a window from Atom Editor
on my computer; This is the same module file that we used for the Codio
video, and you'll notice it looks pretty much the same. Another thing that's
nice about Atom Editor is it has the best Python support out of the box.
While VS Code can support Python, you have to install a lot of extra
features to sort of get it up to speed. And finally, Atom Editor looks pretty
much the same on all computers. I can do demos here on my Mac, but
rest assured it would look the same as if I had done these demos on my
Windows computer as well. To install Atom Editor, you should just go to
the link that is provided on the Canvas web page. Here we have gone to
the Atom page, and you'll notice that when you go there, it will detect
your operating system. It detects that I'm currently running my Macintosh.
We can download this and install it. You should go ahead and you should
install these things. This is a relatively simple install. We don't have to go
through the step-by-step processes that we did with Python, but make
sure that you sort of pick the version that fits your operating system. In
the next two videos, we'll actually talk about how to use these things on
the various operating systems. We'll have one video for Mac and Linux,
which are very similar, and then we'll have a separate video for Windows.
In addition, we'll also show you how to integrate the Terminal or
command line for your operating system with your code editor.
Video Transcript
Installing Atom Editor on Mac or Linux is actually very easy, right? You
just download a file which you can now click on in order to start it up. In
our case, what we've done is we've actually installed Atom Editor and I've
put it in my dock. If I click on it to open it up, you'll now notice that Atom
Editor has launched, and it starts with a bunch of windows. Now, these
windows are meant to welcome me, but if we don't get rid of them
properly, they're going to show up every single time that we run the
application, and that can be a little annoying. OK; so the very first thing is,
we don't actually want the welcome guide to show up every single time
that we're running Atom, so we're going to click that box and now get rid
© 2019 eCornell. All rights reserved. All other copyrights, trademarks, trade names, and logos are the sole property of their respective owners.
Python Fundamentals
Cornell Computing and Information Science
So I'm sitting here, I'm in the Text Editor, I can type things, whatever I
want, but I don't actually want to do that right now. What I actually want to
do is I want to open up a file that I've already created. What I can do that,
is I can go to the File menu, I can select "Open," and now I have a
choice, and what I have is two modules that I have created for this
particular unit. I'm going to click on one and I'm going to open it, and now
you'll notice that I have a module with several assignment statements in
it, each assigning the variables x, y, and z. That's one thing. You'll notice
that the file has been opened, but in addition, Atom Editor did one other
thing when I opened up this file. You'll notice that the tab here to the left
displays the module1.py that I opened, but it also shows module2.py, and
module2.py was in that same folder. In fact, if we go onto the desktop
and we look at the course folder, we go into module5 in unit2, which is
where we're working, you'll notice that indeed there is a module1 and a
module2. There's also this .DS_ Store, which is an invisible file that often
© 2019 eCornell. All rights reserved. All other copyrights, trademarks, trade names, and logos are the sole property of their respective owners.
Python Fundamentals
Cornell Computing and Information Science
appears on Macintosh systems. This can be safely ignored. But the nice
thing about this is because it opened up the folder, if I now want to open
up module2, I just click on it and it will now open up that as well in its own
tab. Why does Atom Editor do this? Because this is a very natural way to
program in Python. Typically, when we're working with Python, we'll have
a folder and we'll organize several related Python files in that one folder,
and then instead of just working on one file, we actually want to open up
the entire folder and quickly jump back and forth between all of these
files.
All right. So that's one way that we can open up a file in Atom Editor.
Another way is just sort of the obvious way that works on most operating
systems these days. If you just take the file and you drag it onto the icon
for Atom Editor, you'll notice that that will open that up as well. OK; so
now that we know how to use Atom Editor, let's put this together with the
Terminal. We start up the Terminal. We now want to access this module,
so what do we need to do? Well, we need to access the file, so we have
to go onto the desktop. On the desktop, we have a folder for the course,
so we change there. Inside of that course, we have a folder for module5,
which is this course module. And inside of that, we have a folder for
unit2, which is indeed the module that contains the file that we want. We
can now start up Python, and now we can safely import the module. And
now we can access each of the variables. So we can look at x, and that
is the value 1. We can look at y, and that is the value 2. And all of this is
fine, except for that we had to do a lot of typing in order to get here. So
that's really annoying. So instead, this is what we remember with the
drag-and-drop trick that was shown in an earlier video. Remember that
Python files are organized together in a folder. So what we do is we take
the folder that contains them and we drop it onto the Terminal. Right
away, we can see that now we're immediately in the folder that we want,
so we can start up Python and import the module right away without any
problems.
In this video, Professor White describes how to set up and start using
Atom Editor on a Windows machine.
Video Transcript
Finally, there's the welcome guide. This is very useful and you're free to
go through this if you want, but we're not going to actually spend much
time on this, so we're going to close this once again. Instead what we're
going to do is we're going to open up the settings. You can get the
settings by either going File>Settings, or as you can see, you can use
control-comma. We're going to open this up, and you'll notice that we
have several options here. We have the editor; this is where we can do
things like setting our default settings. Like right now the font is set to be
14 points, which is a nice-size font for my eyes. But more importantly,
what we're going to do is we're going to look here at the themes. Now, as
you'll notice, Atom Editor uses a dark theme. And dark themes are very
much in vogue these days; a lot of people do find them easier on the
eyes. But personally I'm sort of old school; I still like a light style. It's a lot
easier to teach or project with a light style, and more importantly it will
also match Codio a little better. So I'm going to go to the UI Theme, I'm
going to change it to "Atom Light," and then I'm going to change the
Syntax Theme to match. Now, if you like using a dark theme, that's
perfectly fine; you can go back and change this at any time. I'm just
showing you the option here. But now we're done, and let's close the
© 2019 eCornell. All rights reserved. All other copyrights, trademarks, trade names, and logos are the sole property of their respective owners.
Python Fundamentals
Cornell Computing and Information Science
settings. OK; so now we're in our text editor and we could type whatever
it is that we want. But I don't actually want to do that; I actually want to
open up a file that I have available. In particular, I want to open up one of
the files here in the CIS551 directory in module5 in unit2, which is where
we are right now.
So, one way that I could do this is I could choose "Open File" from the file
menu. And now I can go into CIS551>module5>unit2, and now I'm going
to open up the file module1. And now what you see is that I have this
module open in front of me. And it has several assignment statements for
x, y, and z. But one of the things you'll notice is it didn't just open up this
file. Here I have the file open and I can edit it. But to the left, what it did
was it actually opened up the entire folder unit2. Here to the left, you see
the folder unit2, which has module1 and module2 in it, and here I have
module1 and module 2. So if I wanted now to open up module2, all I
have to do is double-click on it in this pane and it will open up this file as
well. This is very, very useful. Why is that? Because when we're
programming, we're often working on several related files and they're all
organized together in one folder. So it is a natural way of programming
that when I open up a file to open up that entire folder so that I have
access to all of the files at that time. OK; well, so obviously, that's one
way to open up these files. But if I close them, another way that I could
open them is just like we have on any normal application, which is I could
take these files that are inside of the Windows Explorer and I could drag
them onto the icon. And when I do that, once again that will open it up in
the file as well. OK; so now that we know how to use Atom Editor, we're
ready to integrate this together with the PowerShell. Let's open up the
PowerShell, and what we want to do is we want to access module1. But
the first thing that we need to do is we need to navigate to the right
directory. So, we need to go to the desktop, and on the desktop you'll
notice that we have a folder for this course. So let's go to that course.
Inside of there, there's a folder for module5, which is for this course
module. And inside of module5 is a folder called unit2, which is the
current unit. And inside of there are the files module1 and module2.
We're going to start up Python, and now we can import the file module1.
We look at them. Inside of module1, we can access the variable x, which
has a value of 1. We can also access the variable y, which has a value of
2. All of this is well and good, but it was really annoying to have to do all
of those directory changes. So remember, what we can do is the drag-
© 2019 eCornell. All rights reserved. All other copyrights, trademarks, trade names, and logos are the sole property of their respective owners.
Python Fundamentals
Cornell Computing and Information Science
and-drop trick which we showed in the earlier course module. Let's close
the PowerShell and let's open up a new version of it. And now what we're
going to do to do the drag-and-drop trick is we're going to type the word
"cd" and a space. And now, remember, what we have to do is we don't
want to drag the file; we have to take the folder, which in this case is
unit2, that contains those two files. We're going to drag that folder onto
the PowerShell. That's going to put some text, and we're going to hit
Return. Now we are indeed in the right folder. We can start out Python,
and we can import module1.
© 2019 eCornell. All rights reserved. All other copyrights, trademarks, trade names, and logos are the sole property of their respective owners.
Python Fundamentals
Cornell Computing and Information Science
For this assignment, we are not asking you to make a new module from
scratch. Instead, we want you to take an existing module file, modify the
file, and then use the modified module. For this assignment, you may use
whatever environment you are most comfortable with: Codio or your
personal computer.
Using either Codio or the module5 folder you created for Importing a
User-Defined Module, navigate to the folder unit2. Inside you will see a
file called module.py. Do the following:
When you are done, take a screenshot of your code editor side by side
the command shell. On Codio, this will look something like this:
© 2019 eCornell. All rights reserved. All other copyrights, trademarks, trade names, and logos are the sole property of their respective owners.
Python Fundamentals
Cornell Computing and Information Science
© 2019 eCornell. All rights reserved. All other copyrights, trademarks, trade names, and logos are the sole property of their respective owners.
Python Fundamentals
Cornell Computing and Information Science
© 2019 eCornell. All rights reserved. All other copyrights, trademarks, trade names, and logos are the sole property of their respective owners.
Python Fundamentals
Cornell Computing and Information Science
In this video, Professor White describes the coding expectations that will
be part of the final project and walks through elements of working in a
Python file.
Video Transcript
Now that you know how to edit a Python file, you're ready to start working
on the final project for the course. In this project, you're going to be
creating a sequence of Python files, one built on top of the other. And in
the end, you're going to have a complete program. Now, these videos are
not going to take you step by step through the project; we want you to
work on this on your own. But we are going to cover the basics that you
need to know in order to understand what to do. In this video, we're going
to go a little deeper into the idea of modules and look at what are the
types of things that we can actually write in a Python file. For this
particular video, we have a directory called unit3. And inside of unit3, we
have three Python files: module1.py, module2.py, and temp.py. Right
now, we're looking at the module file module1.py. And it looks a little
familiar to some of the modules that we've seen before. As you can see
highlighted here, we do have some assignment statements.
© 2019 eCornell. All rights reserved. All other copyrights, trademarks, trade names, and logos are the sole property of their respective owners.
Python Fundamentals
Cornell Computing and Information Science
There are other seemingly useless statements in this file as well. You'll
notice that there's this thing right here that starts with a hashtag saying, "I
am a comment." What is a comment? A comment is essentially a note to
yourself to allow you to know things about the program, because not
everybody can read Python right away, so maybe I want to write
something in English to let me know what's going on. This particular
comment is what is known as a single-line comment. That's because
Python sees that the comment begins as soon as it sees the hashtag.
Therefore, everything after the hashtag is ignored. But when I come to
the next line, Python is ready to start receiving Python commands; again,
it's no longer actually treating this as a comment. Finally, up at the top of
the file, you'll see something that, once again, it looks like a comment. I
have some notes to myself. I even have, "Hey, I'm the person that wrote
this file, and this is the date that I worked on this particular file." But this
comment lasts for multiple lines. And the reason why Python realizes that
it lasts for multiple lines is because of these quotes at the beginning and
end. It starts with three quotes, and it ends with three quotes. This is
actually a special type of string known as the docstring. And it's called
that because it's for documentation. It's where I write things to help me
understand what's going on with the file in addition to, OK, when it was
that I worked on the file and who was the person that worked on it. The
docstring is like a comment, in the sense that you might think that, OK,
Python is going to look at this and it's going to ignore this because it's a
note to myself. But the docstring is a little more important than that.
Remember that we've shown you the purpose of the help() function,
© 2019 eCornell. All rights reserved. All other copyrights, trademarks, trade names, and logos are the sole property of their respective owners.
Python Fundamentals
Cornell Computing and Information Science
which I can use to get help on any module. So I'm going to type "help",
and I'm going to ask for help on module1. And if we look very, very
closely, we'll notice, well, it's not exactly in the same format, but a lot of
the things that we see inside of our docstring are here on the screen,
right? A simple module, this description saying that it's a file that shows
how modules work, and this is the author, and this is the date. So
actually, the docstring is one of the most important things that you can
ever write inside of a module, because if somebody else is going to use
this module that you've created, you are essentially creating the help
instructions for them to use.
Video Transcript
We've seen that a Python module can contain any sort of statements.
Expressions are ignored, but any sort of statements can be processed.
Now, the primary statement that we understand is the assignment
statements, so so far all of our module files have been creating variables.
But that's not the only type of statement that we know. There is another
statement, which is the import statement. The import statement is what
allows us to access additional functions. When we import the "math"
module, we get access to extra functions, like sine() and cosine().
Because this is a statement, we can actually do this in another module
file. So one module can import another. Inside of the directory unit3,
you'll notice that we have a file called module2.py. This is very similar to
the modules that we've seen before. There are a lot of comments here
that are just notes to myself. But right away, we'll see that we actually
have two statements right here. The first is a statement to import the
module "math". Once I've imported the module "math", I now have
access to the function cosine(). I'm going to call the value of the function
cosine() on the value of zero; that's going to compute an answer, and
that's going to put that inside of the value x. Why don't we import the
module? Let's see what happens. We start Python and we import
module2. Remember that when you import a module, what Python does
is it goes through in order and it executes all of the statements. So it's
going to execute that statement "import math", and it's going to assign
the value to x. And right away, if we look at what the value of x is, we'll
see that it is 1, which is indeed what cosine of zero is.
Now, that's not the only module that we imported inside of module2; we
© 2019 eCornell. All rights reserved. All other copyrights, trademarks, trade names, and logos are the sole property of their respective owners.
Python Fundamentals
Cornell Computing and Information Science
© 2019 eCornell. All rights reserved. All other copyrights, trademarks, trade names, and logos are the sole property of their respective owners.
Python Fundamentals
Cornell Computing and Information Science
Coding a Module
© 2019 eCornell. All rights reserved. All other copyrights, trademarks, trade names, and logos are the sole property of their respective owners.
Python Fundamentals
Cornell Computing and Information Science
Note for Mac users: If you have installed a Python version newer
than 3.6.6, do not run the hello_app.py script on your machine, as it
may cause a crash.
Video Transcript
We've talked about two different types of Python files: the module and
the script. What is the difference between the two of these? So, to
understand that, why don't we step back and sort of think about the
different ways that we would interact with Python. One of the ways that
we've been interacting with Python has just been running Python
interactively; typing the word "python" by itself and then typing
commands. This is where modules were very, very useful, because if I
wanted to have extra functionality, I would import a module file and that
would give me extra functions. So, in particular, in this case, I have my
module "temp", which allows me to have my temperature conversion
functions. And I can call a function like temp.to_centigrade(), and that's
going to convert from Celsius to Fahrenheit. That's one particular Python
file. However, you'll notice that in this directory, in addition to "temp", I
have another file called hello_app. This file is one that I would use in a
very, very different way. Instead of using Python in the interactive mode, I
would run it as a script, which means that I type the word "python" and
now I'm going to type the name of the file, including the .py. Notice what
happened. This case, Python has actually shown me this nice little
window on the screen that has the phrase sort of "Hello World!" in it. And
I can close this window, and it's all done. This is an example of a script.
It's like an application; I can use it for doing nice graphical things. But the
interesting thing to notice is that hello_app.py and temp.py both end in
© 2019 eCornell. All rights reserved. All other copyrights, trademarks, trade names, and logos are the sole property of their respective owners.
Python Fundamentals
Cornell Computing and Information Science
So how can I tell the difference between them? Well, actually, the
difference between a module and a script has very little to do with the file
itself. It's actually how I use it. If I wanted to, I could start up Python, be in
the interactive shell, and I could "import hello_app" as a module if I
wanted to. I didn't get an error here; Python happily imported this
particular file as a module. Nothing seemed to happen; that's because
this file isn't really designed to be used as a module, but I can use it as a
module if I wanted to. Similarly, I can quit Python, and now I can run
"temp" as a script. Once again, I would type the word "python" followed
by the name of the file. including the .py. I'm going to hit Return. I didn't
get an error; nothing weird happened, but nothing really happened at all.
And that's because, once again, temp.py is designed to be used as a
module and it's not really designed to be used as a script. So, modules,
scripts; the files look the same. The only difference is how you use them.
But as I said, certain files are designed to be used as modules and
certain files are designed to be used as scripts. So what's really the
difference between them? Well, let's return to the file module1, which
we've seen before. This file has two assignment statements for the value
x, and at the end it has x by itself.
© 2019 eCornell. All rights reserved. All other copyrights, trademarks, trade names, and logos are the sole property of their respective owners.
Python Fundamentals
Cornell Computing and Information Science
This didn't actually import silently like module1; you'll know right away
that it actually displayed the value of 9 on the screen. And in fact, if I
asked "script", "What is the value of x?" you'll notice that that has the
value of 9. That's because since there's this print() statement at the end,
Python knows that one of the things it needs to do when it's executing the
lines of code in the file is to do this print(); to display something on the
screen. Now, normally we don't want our modules to do this, but one of
the nice things about having this print() statement is, this means that I
can now use this file, which looks almost exactly like module1 but for this
one little difference, as a script. Let's quit Python. And now I'm going to
use this file as a script; I'm going to type the word "python" and the name
of the file, including the .py. And notice that this time something
happened. If I were to run module1 as a script, it wouldn't do anything,
but when I ran "script", it displayed the value of 9, and that's because it
had this print() statement to show something on the screen. This is the
primary advantage of printing, right? Printing is something that we're
going to be using in the final project to allow you to write scripts so that
you can display things on the screen. As a general rule, this is pretty
much what the difference between modules and scripts are. Scripts will
contain certain functions or statements that are designed to be shown
outside of the Python environment, whereas modules are designed to be
run silently. But other than that, it's really a difference in how you use the
two files.
© 2019 eCornell. All rights reserved. All other copyrights, trademarks, trade names, and logos are the sole property of their respective owners.
Python Fundamentals
Cornell Computing and Information Science
Coding a Script
Coding a Script coding exercise
© 2019 eCornell. All rights reserved. All other copyrights, trademarks, trade names, and logos are the sole property of their respective owners.
Python Fundamentals
Cornell Computing and Information Science
In this video, Professor White introduces the Python Tutor and shows
how it can help you see what's happening under the hood.
After you have watched the video, you can access the Python Tutor here
or from the next page.
Video Transcript
When we run a script, unlike in the interactive shell, we don't really see a
lot. I mean, certainly we see any print() statements that might be in the
file, but we don't really get to see any of the variables, and we don't see
any of the function calls, and we don't get the step by step that we get
when we're working with the Python interactive shell. And this can make
it a bit hard to find bugs, particularly when you're working on a project
that is pretty complicated and has a lot of files. Once again, this is an
argument for visualization, and this is one of the reasons why we had you
visualize assignment statements in a previous course module. But what
would be nice is if we actually had a tool to help us with that visualization;
something that we, say, could maybe copy a script or module in and
actually see these variables that are being created. We do have such a
tool; it's known as the Python Tutor. There are a couple of versions of the
Python Tutor out there, but the version that we're going to be using is
specially designed for this course. It's a web page and it's linked to from
the Canvas web page, and when you click on this link, you'll get this
particular web page that we have in front of us which says the "eCornell
Python Tutor." What you'll notice here is that I have a box. This box is
very similar to working inside of a Python file; I can type Python code,
and I can execute this code. In this case, it's not really going to do a lot
when I actually execute, but if I had a print() statement here, if I were to
execute the code, you'll notice that it printed out a 2, just like when I
would run a script. The only things that I can see are the print()
© 2019 eCornell. All rights reserved. All other copyrights, trademarks, trade names, and logos are the sole property of their respective owners.
Python Fundamentals
Cornell Computing and Information Science
If I want to execute that line of Python code, I just hit the "Forward"
button. And notice what happens. This is an assignment statement. An
assignment statement creates a variable, which is a box, with a name,
with stuff in it. And that's actually what's happened; the types of things
that we were doing in our visualization exercises are done for us here on
the screen. However, I'm still not done with the file; you'll notice that
there's a red arrow here at this print() statement, and that means that,
once again, it's ready to go ahead and execute that as soon as I tell it to.
I'm going to hit the "Forward" button again, and now you'll notice that it's
printed out the value 2 on the screen, just like it would in the script. And
here I have that it says, "Program terminated"; that means that it has
reached the end of the file. So what you'll notice about here is the nice
thing about the Python Tutor is it allows me to go through complex files
one line at a time and see what's going on. Let's take our script file, which
has our two assignment statements and a print() statement, and let's just
copy this here into the area that will take code. And now let's hit
"Visualize". Right away, you'll notice that the red arrow has reached the
end of the docstring; that's because docstrings are never executed. So
we're just going to go ahead to this line right here, and the red arrow says
now it's ready to execute the assignment statement for x. We're going to
click "Forward" and it's going to create my variable x for me with a value
3 in it. The red arrow is in front of the second assignment statement. I'm
going to click "Forward", and notice that it changed the value of the
variable for x. Finally, the red arrow is in front of the print() statement; we
go forward, it prints out that value, and it tells me that the program has
terminated, telling me that I'm at the end of the file. This is a very
valuable tool, and you might find this tool useful when you are working on
your semester project. One last thing to know about this particular
visualization tool is you'll notice that there's some tabs up here. The
reason why it supports tabs is, we pointed out that modules can import
other modules. Well, we could do that. If I wanted to call a module, say,
"module", I would rename the tab. I'm going to do an assignment
statement here of "y = 3". And now I can go inside of this module, and I
can import the first module. What that's going to do is that's going to
© 2019 eCornell. All rights reserved. All other copyrights, trademarks, trade names, and logos are the sole property of their respective owners.
Python Fundamentals
Cornell Computing and Information Science
execute all of the code inside of this tab, and now I have access to it, like
this. Let's "Visualize". Now, you'll notice that when it imports the module,
it still does that silently. The only thing that we can visualize is the first tab
that is selected. However, it did execute that line of code, and I now do
have a variable y inside of "module", which I can assign to the value of x.
© 2019 eCornell. All rights reserved. All other copyrights, trademarks, trade names, and logos are the sole property of their respective owners.
Python Fundamentals
Cornell Computing and Information Science
© 2019 eCornell. All rights reserved. All other copyrights, trademarks, trade names, and logos are the sole property of their respective owners.
Python Fundamentals
Cornell Computing and Information Science
Visualizing a Script
For this assignment, you are going to work with the Python Tutor that is
part of this course module. We want you to visualize the script die.py that
you made for Coding a Script. As part of this assignment, you should do
the following:
1. Copy the contents of the file die.py into the Python Tutor text box.
2. Click the Visualize button.
3. Take a screenshot of what you see.
4. Press the Forward button.
5. Repeat 3 & 4 until it says Program Terminated.
You do not need to make the screenshots pretty and assemble them into
a PDF (though you can if you want). The easiest way to submit this
assignment is to put the screenshots into a folder and then create a ZIP
file from that folder. Both MacOS and Windows can create ZIP files by
right-clicking on the folder. For MacOS, the option is Compress. For
Windows, it is Send to > Compressed Folder.
© 2019 eCornell. All rights reserved. All other copyrights, trademarks, trade names, and logos are the sole property of their respective owners.
Python Fundamentals
Cornell Computing and Information Science
In this video, Professor White introduces a function that enables this user
interaction and provides the last piece you need to begin your course
project.
Video Transcrpt
Right now our scripts aren't really interesting, and that's because they
pretty much do the same thing all the time. I mean, they can do some
calculations and they print something at the end, but because that's all
we know how to do, they're always going to print out the same thing. So
let's suppose we have sort of the script.py file that we've been working
with for a while that assigns some values to x and prints out a result at
the end. If I were to run this as a Python script, I'm going to get the value
9. I run it again, I get the value 9. Every time I run it, I'm going to get the
value 9. It's not particularly interesting. That's not how programs work,
right? Programs typically interact with the user in some way. The user
gives some form of input, moving a mouse or typing something, and the
program does something different each time in response. In order to do
that, we're going to introduce a new function which is called the input()
function. Before we show it in a script, let's work with this in the
interactive shell first. So what we're going to do is we're going to start up
Python and we're going to call the function input(). Remember, we use a
function by typing its name, and I'm going to put in here, in the string,
"Type something".
Now I'm going to hit Return. You'll notice that "Type something" is
displayed on the screen. So input() kind of works like print(), right? It's
displaying something on the screen. But it hasn't moved me to the next
line, and I don't see the three greater-thans anymore, so it kind of looks
like I'm stuck. Well, maybe if I type something; let's hit Return. This is
really interesting. Notice that everything that I typed after "Type
something" is now given back to me as a string. And that's because
© 2019 eCornell. All rights reserved. All other copyrights, trademarks, trade names, and logos are the sole property of their respective owners.
Python Fundamentals
Cornell Computing and Information Science
So now let's put all of these together, and what we're going to do is we're
going to write a rather interesting script. So this is the file "next", and
what the idea is is that I'm going to type a number and Python is going to
give me the next number that follows it. Now look at this, right? We have
several assignment statements, and it ends with a print() statement at the
end, just like several of the script files that we've used before. At the very
beginning, I'm asking the user to give me a number, and I'm going to put
that inside of the variable x. Then I'm going to take — well, x currently
has a string, and I'm going to convert that to an integer, and then I'm
going to add 1 to it and I'm going to put that inside of the variable y. So
let's see this in practice. Let's quit and let's run "next" as a script. All right.
It asked me for a number. I'm going to type 12, and it tells me that the
next number is 13. And every single time I run this, if I give a different
number, it's going to give me a different answer each time, which is
exactly what I want with the script. Now, notice that in this case the only
things that I can see are input() and print(). There's a lot of other things
going on in the background with all of these assignment statements, but
© 2019 eCornell. All rights reserved. All other copyrights, trademarks, trade names, and logos are the sole property of their respective owners.
Python Fundamentals
Cornell Computing and Information Science
you don't see those happen when you run Python. If I wanted to see
these, well, then we would go back to the visualization tool that we saw in
a previous video. So here we are; we're looking at the Python Tutor, and
you'll notice that I have copied this interactive script into the window. And
let's hit "Visualize". So the red arrow comes before the input(), and look
at this; it pops up a little window to ask me to type in the input. So I'm
going to hit 12 and I'm going to hit "Submit". And what it did was it
created the variable x and it has put 12 as a string inside of that variable.
Now I'm going to execute the next line. It's going to take x, convert it to
an int, and it's going to put that value back into the variable x. Now "y =
x+1", so it's going to create the variable y and put 13 in it, and at the very
end it's going to print it out. And this is all you need to know in order to
complete the final project for the course.
© 2019 eCornell. All rights reserved. All other copyrights, trademarks, trade names, and logos are the sole property of their respective owners.
Python Fundamentals
Cornell Computing and Information Science
© 2019 eCornell. All rights reserved. All other copyrights, trademarks, trade names, and logos are the sole property of their respective owners.
Python Fundamentals
Cornell Computing and Information Science
© 2019 eCornell. All rights reserved. All other copyrights, trademarks, trade names, and logos are the sole property of their respective owners.
Python Fundamentals
Cornell Computing and Information Science
© 2019 eCornell. All rights reserved. All other copyrights, trademarks, trade names, and logos are the sole property of their respective owners.
Python Fundamentals
Cornell Computing and Information Science
Walker M. White
Senior Lecturer and Stephen H. Weiss Provost's Teaching Fellow
Cornell Computing and Information Science
Cornell University
Sincerely,
Walker M. White
© 2019 eCornell. All rights reserved. All other copyrights, trademarks, trade names, and logos are the sole property of their respective owners.
Glossary
Accumulator
An accumulator is a variable in a for-loop that stores information computed by the for-loop and will be still
available when the for-loop is complete. For example, in the code
total = 0
for x in range (5):
total = total + x
Application
An application is another name for a script.
Argument
An argument is an expression that occurs within the parentheses of a method call. The following call has two
arguments: x+y and y+w:
min(x+y, y+w)
As a general rule, the number of arguments should equal the number of parameters that are called, except
when using default arguments.
Assert statement
An assert statement is a statement in Python used to enforce an assertion. It has one of the following forms:
assert <bool>
assert <bool>, <message>
In both cases, Python evaluates the boolean expression. If the expression is True, nothing happens. If it is
False, Python will raise an exception with the (optional) provided message.
Assignment statement
An assignment statement is a statement with the following form:
<variable> = <expression>
If the variable does not yet exist, the statement creates the variable and stores the given value inside it. If the
variable does exist, then it replaces the old value with the one provided.
Basic type
A basic type is any type that has a corresponding literal. Basic types are fully integrated into Python (they
do not require an import statement to use) and are not mutable. In Python, the basic types are int, float,
bool, complex, and str.
Bool
A bool or boolean is a basic type whose values are True and False.
Bug
A bug is an error in a program.
Call frame
A call frame is an area of memory created whenever a function is called. The call frame contains the
following:
The call frame changes over time as the function executes, adding, changing, or deleting variables.
Call stack
A call stack is the area of memory containing all active call frames. The call frames are arranged top to
bottom with the most recent call on the bottom of the stack. A call frame may not be erased until all call
frames below it are erased.
Cast
A cast is an operation that converts a value from one type to another. For example, the cast float(5+6)
converts the value of the expression, which is 11, to float format.
A widening cast converts from less information to more information and can be done implicitly. A
narrowing cast must be done explicitly because it may lose information or may be illegal. See narrower type
for more information.
Command shell
The command shell is an OS-specific application that responds to text commands. On Windows, it is called
the PowerShell. On MacOS (and most Linux systems), it is called the Terminal.
Comment
A comment is a line of code that is ignored by Python and only serves as a note to the programmer. Most
comments start with a #. We sometimes refer to docstrings as comments. However, these are not actually
ignored because they are used by the help()function.
Conditional expression
A conditional expression is an expression with the following form:
To evaluate this expression, Python first evaluates the boolean expression <bool>. If the boolean is True,
Python uses the value of <expr1> as the value of the conditional expression. Otherwise, Python uses the
value of <expr2> as the value of the conditional expression.
Conditional statement
A conditional statement is a statement of the form
if <bool>:
<statements>
Python executes this statement as follows: If the boolean expression is True, if executes the statements
underneath. Otherwise, it skips over them.
if <bool>:
<statements>
else:
<statements>
This form is executed as follows: If the boolean expression is True, it executes the statements underneath
the if. Otherwise it executes the statements underneath the else. There are additional forms of conditional
statements that use the keyword elif.
<classname>(<arguments>)
For example, Point (1,2,3) is a constructor call for the class Point.
Debugging
Debugging is the act of searching for and removing bugs in a program.
Default argument
A default argument is an argument that is provided automatically if it is omitted in the function call. Default
arguments are specified by writing the associated parameter in the form of an assignment statement. For
example, the following function header has a default argument for y:
def foo(x,y=2):
In this case, the function call foo(1) is legal; the y parameter is given the default argument 2. In this
course, we are primarily interested in object and class folder.
Dict
A dict or dictionary is a mutable type that associates keys with values. It is similar to a sequence, except that
elements are accessed by the key, not the position. For example, in the dictionary
d = { ‘alpha’:1, ‘beta’:3 }
Docstring
A docstring is a string literal that begins and ends with three quotation marks. Document strings are used to
write specifications and are displayed by the help() command.
New-Line Character \n
Backslash Character \\
Double-Quote Character \”
Single-Quote Character \’
Evaluate
Python evaluates an expression by turning it into a value.
Float
A float is a basic type whose values are scientific numbers like 3.46E-4.
For-loop
A for-loop is a statement of the form
Python executes this statement as follows: It puts the first element of the iterable in the variable, and then
executes the statements indented underneath. It repeats this process as long as there are still elements
left in the iterable.
In a for-loop, the variable after the keyword for is called the loop-variable while the iterable is called the
loop-iterable or loop-sequence.
Fruitful function
A function that terminates by executing a return statement, giving an expression whose value is to be
returned. Fruitful functions (possibly) return a value other than None.
Function
A function is a set of instructions to be carried out via a function call. You can think of it like a recipe in a
cookbook. We often separate functions into fruitful functions and procedures.
Function body
The function body consists of the lines of code specifying what is to be done when the function is called. The
function body appears indented after the function header. We typically use the term function body to just
refer to the actual Python code and exclude the function specification.
<function-name>(<arguments>)
It is important to understand how a function call is executed. Its execution is performed in five steps:
If the function is a fruitful, it returns the value of the appropriate return statement. If it is a procedure, it
returns None.
Function definition
The function definition is the code that tells Python what to do when a function is called. It consists of the
function header and function body.
Function frame
A function frame is another term for a call frame.
Function header
The function header is the part of the definition that starts with the keyword def, followed by the function
name and the parameters delimited by parentheses. The function body is immediately indented underneath.
Function name
The function name is the name used to call a function. It appears in the function header, immediately
after the keyword def.
Function specification
The function specification defines what the function does. It is used to understand how to call the function. It
must be clear, precise, and thorough, and it should mention all parameters, saying what they are used for. It
should also include a precondition for each parameter.
In Python, function specifications are written with a docstring. They appear immediately after the function
header, indented with the function body.
Global space
Global space is the region of memory that stores global variables.
Global variable
A global variable is a variable that is defined outside of a function or class definition. Typically, both function
names and module names are global variables; these variables each contain the identifier of the folder that
stores the function or module content in the heap.
Heap
The heap is the region of memory that stores all folders. Anything that is not a basic type must be
represented as a folder in the heap.
Immutable
The adjective immutable means “incapable of being changed.” It is typically used to refer to an attribute or
a type.
Immutable attribute
An immutable attribute is a hidden attribute that has a getter but no setter. This implies that a user is not
allowed to alter the value of this attribute. It is an important part of encapsulation.
Immutable type
An immutable type is any type that is not mutable. All of the basic types are immutable.
implementation
An implementation is a collection of Python code for a function, module, or class that satisfies a specification.
This code may be changed at any time as long as it continues to satisfy the specification.
In the case of a function, the implementation is limited to the function body. In the case of a class, the
implementation includes the bodies of all methods as well as any hidden attributes or methods. The
implementation for a module is similar to that of a class.
It is used to access the global variables, functions, and classes defined within a module. When we import a
module, all module variables (and function and class names) are stored in a folder. Unless the from syntax is
used, all content must be accessed using a variable with the same name as the module.
import math
then we write math.pi to access the variable pi in this module. On the other hand, if we write
then all of the contents of the module math are dumped into global space. In that case, we only need to write
pi to access the same variable.
Instance
An instance of a class is an object. The terms instance and object are synonyms. We typically use the word
instance when we are referring to a collection of objects all of the same class.
Instantiate
The word instantiate means “to create an instance of.” Evaluation of a class expression C(...) instantiates
an instance of the class C.
Int
An int is a basic type whose values are integers.
Interactive shell
The interactive shell is a program that allows the user to type Python expressions and statements one at
a time, evaluating them or executing them after each step. It is not to be confused with the command shell,
which is a more general purpose tool. However, the interactive shell is often run within the command shell.
For a function, the interface is typically the specification and the function header. For a class, the interface is
typically class specification as well as the list of all unhidden methods and their specifications. The interface
for a module is similar to that of a class.
Is
The is operator works like == except that it compares folder names, not contents. The meaning of this
operator is can never be overloaded.
Iterable
An iterable type is the type of any value that may be used in a for-loop. Examples include lists, strings,
and dictionaries.
Keyword
A keyword is a special reserved word telling Python to do something. Examples include if, for, and def.
Keywords may not be used as variable names.
List
A list is a mutable type representing a sequence of values. Lists are represented as a comma-separated
sequence of expressions inside square brackets, like this
Literal
A literal is a way to represent a value in Python. Literals are used to write expressions with any of the basic
types. Here are several examples of literals:
int 354
float 3.56
complex 3.5j
bool True
str “Hello World!”
str ‘Hello World!’
Local variable
A local variable is a variable that is created within the body of a function or method.
Loop iterable
A loop iterable is the entity that produces values for a for-loop. Because most loop iterables are sequences,
this term is often used interchangeably with a loop sequence.
Loop sequence
A loop sequence is the entity that produces values for a for-loop. The name is chosen because most of the
time for-loops use a sequence. However, the term loop iterable is more accurate.
Loop variable
A loop variable is a variable that acquires the next element of the loop iterable through each iteration of a
for-loop. In some cases, the term loop variable is extended to include any variable that appears in the loop
condition of a while-loop.
Method
A method is a function that is contained within a class definition. Methods are able to access the attributes of
the class, in addition to the parameters and local variables that any function can access.
Method call
A method call is a function call for a method. It is similar to a function call except that it has the following
form:
<folder>.<method-name>(<arguments>)
where <folder> is an object in the case of an instance method and a class in the case of a class method.
A method call creates a call frame exactly like a function call except that the folder name of <folder> is
assigned to self.
Module
A module is a file containing global variables, function definitions, class definitions, and other Python code.
The file containing the module must be the same name as the module and must end in .py. A module is used
by either importing it or running it as a script.
Module specification
A module specification is a description of the purpose of a module and how to use it. Module specifications
are typically written using docstrings.
Mutable attribute
A mutable attribute is an attribute that can be freely changed. Mutable attributes need not be encapsulated.
But if the attribute is hidden, then it will need both a getter and a setter.
Mutable type
A mutable type is a type where the values are containers and it is possible to alter the contents of the
container. An int is not mutable because it does not contain anything; it is just a number. A string is a
container of characters but it cannot be changed. The types list and dictionary are examples of mutable
types, as are most user-defined classes.
Narrower type
A narrower type is a type for which Python will perform a cast from automatically. In other words, Python will
automatically cast from a narrower type to a wider type. This concept only applies to bool and the numeric
types. The progression below shows the progression from narrowest type to the widest type:
None
The value None actually represents the absence of a value. If Python attempts an attribute reference like
None.b or a method call like None.m(...), it will raise an exception.
Object
An object is an instance of a class. Each object for a class can access the attributes and methods defined in
and inherited by the class.
Object attribute
An object attribute is an attribute that is unique to a specific object and is therefore stored in the
object folder.
Object class
The object class is a special class built into Python named object. It is the superest class of all. Any class that
does not extend another class must extend the object class.
Object folder
The object folder is the folder in the heap that contains the attribute values unique to an object. We use this
term in place of the term object when we want to exclude any attributes or methods that might be inherited.
Object representation
An object representation is a string that can uniquely identify an object. It is retrieved with the repr function.
Parameter
A parameter is a variable that is declared within the header of a function or method.
Pass statement
A pass statement is a statement that tells Python to do nothing. It is used to fill the body of a function stub.
Procedure
A procedure is a function that has no explicit return statement. A function call on a procedure always
evaluates to None.
Return statement
A return statement is a statement that terminates the execution of the function body in which it occurs. If it is
followed by an expression, then the function call returns the value of that expression. Otherwise, the function
call returns None.
Scope
The scope of a variable is the set of statements in which it can be referenced. For a parameter, it is the
corresponding function body. For a local variable, it is from the initial assignment statement until the variable
is deleted, or the end of the function body.
Script
A script is a Python program that is meant to be run outside of interactive mode. In particular, scripts often
have the following line of code to prevent them from being imported:
if __name__ == “__main__”:
To run a script, type python <script> in the OS command shell. When a script is run, it will execute all of the
code indented under the conditional above.
Statement
A statement is a command of Python to do something. Python executes a statement.
Str
A str or string is a basic type whose values are text, or sequences of characters. String literals must be either
in double or single quotes.
Test-case
A test-case is a collection of inputs, together with an expected output, used to test a single run of a program.
It is often used in unit tests to test a function.
Testing
Testing is the act of analyzing a program, looking for bugs. Unlike debugging, it does not necessarily involve
removing bugs.
Try-except statement
A try-except statement is a statement of the following form
try:
<statements>
except:
<statements>
Python attempts to execute all of the statements underneath try. If there is no error, then Python does
nothing and skips over all the statements underneath except. However, if Python crashes while inside the try
portion, it recovers and jumps over to the except. It then executes all the statements underneath there.
Tuple
A tuple is an immutable type representing a sequence of values. Tuples are represented as a
comma-separated sequence of expressions inside parentheses, like this
Typing
Typing is a special form of precondition that requires that a variable hold a value of a specific type. It is the
most common form of function precondition in this course.
Unit test
A unit test is a collection of test cases used to test a unit of code, typically a function or method.
Variable
A variable is named with an associated value. We sometimes refer to it as a named box with the value in the
box. In Python, there are four basic kinds of variable, determined by the memory region they fit in:
• Parameters
• Local variables
• Attributes
While-loop
A while-loop is a statement with the following form:
while <bool>:
<statements>
Python executes this statement as follows: It first evaluates the boolean expression. If it is True, then it
executes the statements indented underneath. It repeats this process as long as the boolean expression is
True. This boolean expression is often referred to as the loop condition.
While-loops are difficult to use properly and are often combined with loop invariants.
Wider type
A wider type is a type for which Python will perform a cast from automatically. In other words, Python will
automatically cast from a narrower type to a wider type. This concept only applies to bool and the numeric
types. The progression below shows the progression from narrowest type to the widest type: