Chapter 1

Basic Python

Subsections of Basic Python

Learning to Program

YouTube Video


Learning to program involves learning not only the syntax and rules of a new language, but also a new way of thinking. Not only do we want to write code that is understandable by the computer, we must also understand what the computer will do when it tries to run that code.

A key part of that is learning to think like a computer thinks. We sometimes call this our “mental model” of a computer. If we have a good “mental model” of a computer, then we can learn to read code and mentally predict what it will do, even without ever running it on an actual computer. This ability is crucial for programmers to develop.

So, as we work through this lab, we’ll need to constantly pay attention to how a real computer works, and make sure that our “mental model” is accurate. If not, we’ll have to adapt our understanding of a computer to match the real world. This process of adaptation and accommodation is an important part of learning to program - we have to have a good understanding of what a computer actually does when it runs our code, or else we won’t be able to write code that will do what we want it to do.

We’ve chosen Python because it is very easy to learn, easy to use, and it is used in many different places, from scientific computing and data analysis to web servers and even artificial intelligence. It is a very useful language to learn, and it makes a great first programming language.

As we learn to write code in a real programming language, it helps to refer to the actual documentation from time to time. So, we recommend bookmarking the official Python Documentation as a great place to start. Throughout this course, we may also include links to additional resources, and those are also worth bookmarking. One of the best parts about programming is that nearly all of the documentation is online and easily accessible, and learning how to quickly search for a particular solution or reference is just as useful as knowing how to do it from memory. In fact, most programmers really only know the basics of the language and a few handy tricks, and the rest of it is just reading documentation and learning when to use it. So, don’t worry about remembering it all right from the start - instead, learn to read the documentation and use the tools that are available, and focus on understanding the basics of the language’s syntax and rules. Let’s get started!

Subsections of Learning to Program

Working in the Terminal

YouTube Video


First, let’s start with the basics of writing Python code in a file and running those files. This is the first major step toward actually writing a real program, but it can definitely be difficult the first time without prior experience to rely on. So, let’s go through it step by step and make sure we know how to run our programs in Python.

At this point, we should already have Python installed on our system. For students using Codio, this is taken care of already. For students using their own computers, refer to an earlier lab to find instructions for installing Python on your system, or contact the instructors for assistance.

To make sure that Python is installed and working, we’ll need to open a terminal in our operating system. In Codio, this can be found by clicking the Tools menu at the top, and then choosing Terminal. More information can be found in the Codio Documentation . There may also already be one open for you if you are reading this content from within Codio.

If you are working on your own computer, you’ll need to open a terminal on your operating system. This should have been covered in the previous lab when you installed Python. On Windows, look for Windows Terminal or Windows PowerShell (not the old Command Prompt, which requires different commands). On Mac or Linux, look for an application called Terminal. Throughout this course, we’ll call these windows the terminal, even though they may have slightly different names in each operating system.

Once we have the terminal open, we should see something like one of these examples:

Linux Terminal Linux Terminal

Windows Terminal Windows Terminal

At this point, we should see a place with a blinking cursor, where we can type our commands. This is called the command prompt in the terminal. The first thing we can do is check to make sure Python is properly installed, and we can also confirm that it is the correct version. To do this, we’ll enter the following command and press enter to execute it:

python3 --version

Hopefully, that command should produce some output that looks like this:

Python Version Python Version

Here, we see that the currently installed Python version is 3.10.6. As long as your Python version number begins with a 3, you have correctly installed Python and are able to run it from the terminal. So, we can continue to the next part of this lab.

If you aren’t able to run Python or aren’t sure that you have the correct version, contact the instructor for assistance!

Python 2 vs. Python 3

Notice that we have to use the command python3, including the version number, instead of the simpler python command here. This is because some systems may also have Python version 2, an outdated version of Python, installed alongside version 3. In that case, the simple python command will be Python version 2, while python3 will be Python version 3. Unfortunately, most programs written in Python 3 will not run properly in Python 2, so it is important for us to make sure we are using the correct Python version when running our programs.

Thankfully, the command python3 should always work, and using that command is a good habit to learn. So, throughout this course, we will use the command python3 to run Python programs.

When we open a terminal, it will usually start in our user’s home folder. This may mean different locations for different operating systems. For example, if our current user’s name is <username>, the terminal will usually start in this location for each operating system:

  • Windows: C:\Users\<username>
  • Linux: /home/<username>
  • Mac: /Users/<username>
  • Codio: /home/codio/workspace

The directory that is open in the terminal is known as the working directory. We can use the pwd command to determine what our current directory is:

Print Working Directory Print Working Directory

In this example, we are looking at the Codio terminal, so our working directory is /home/codio/workspace.

Next, we can see the files and directories contained in that directory using the ls command. Here’s the output of running this command in Codio:

List Directory Command List Directory Command

In the output, we can see that there is a file named README.txt and a directory named python. In Codio, we’ll place all of our files in the python directory, so we can open that using the cd python command:

Change Directory Command Change Directory Command

Notice how the python directory is now included in the command prompt in the terminal. Most terminals will show the working directory in the command prompt in some way.

That’s the basics of navigating in the terminal, but there is much more to learn. If you’d like to know more, consider checking out some of the resources linked below!


Windows & Mac Terminal

Most of the content in this course will focus on using the commands that are present in the Linux terminal, since they are the most widely-used commands across all platforms. In general, these commands should work well on both Windows and Mac, with a few caveats:

  • On Windows, there is an older Command Prompt tool that does not support the newer Linux commands. Therefore, we won’t be using it. Instead, we only want to use Windows PowerShell, which supports most of the basic Linux commands via aliases to similar PowerShell commands. We can also install the Windows Terminal application for a more modern interface.
  • Windows users may also choose to install the Windows Subsystem for Linux (WSL) to run Linux (such as Ubuntu) directly within Windows. Many developers choose to pursue this option, as it provides a clean and easy to use development environment that is compatible with the Linux operating system.
  • The Mac operating system includes a terminal that uses either ZSH (since OS X 10.15) or Bash (OS X 10.14 and below). This terminal is very similar to the Linux terminal when it comes to navigating the file system and executing programs, which is sufficient for this course.

Fully learning how to use these tools is outside of the scope of this class, but we need to know enough to navigate the filesystem and execute the python3 command. If you need assistance getting started with this step, your best bet is to contact the instructors. Each student’s computer is a bit different, so it is difficult to cover all possible cases here.

Subsections of Working in the Terminal

Print Statement

YouTube Video


Before we learn to write our first program, let’s start by introducing some important vocabulary terms:

  • string: A string in programming is any text that is stored as a value. We typically represent strings by placing them inside double quotes "" in our code and elsewhere.
  • value: A value is a piece of data that our program is storing and manipulating. In our pseudocode, values consist of either numbers or strings.
  • keyword: A keyword is a reserved word in a programming language that defines a particular statement, expression, structure, or other use. As we’ll learn later, we cannot use these keywords as variable or procedure names.
  • statement: A statement refers to a piece of code that performs an action, but doesn’t result in any value. Most complete lines of code are considered statements.
  • expression: An expression, on the other hand, is a piece of code that, when evaluated, will result in a value that can be used or stored. An expression can even contain multiple expressions inside of it!

We’ll use these terms to help us understand different parts of the code in our programs. Now that we’ve covered them them, we can start to discuss the various statements in Python.

The first statement that we’ll cover in the Python programming language is the print(expression) statement. This statement is used to display output to the user via the terminal. So, when Python runs this statement, it will evaluate the expression to a single value, and then print that value to the terminal.

For example, the simplest Python code would be a simple Hello World program, where we use the print(expression) statement to display the text "Hello World" to the user:

print("Hello World")

Notice that the expression part of the statement contains "Hello World" in quotation marks? That is because "Hello World" is text, so we should put it in quotes and make it into a string in our code. Also, since the string "Hello World" can be treated like a value, we can also say it is an expression, and therefore we can use it in the expression part of the statement. This may seem pretty straightforward now, but as our programs become more complex it is important to think about what pieces of code can be treated as values, expressions, and statements.

When we run that program in Python, we’ll see the following output:

Hello World

If you look at the output, you might notice something strange - the text on our user interface doesn’t include the quotation marks "" that the expression "Hello World" contained. When we display text to the user, Python will remove the quotation marks from the beginning and the end of the string, and just display the text inside. Pretty handy!

Let’s go through the full process of writing and running that program in Python!

Writing a Python Program

The first step to create a program in Python is to create a text file to store the code. This file should have the file extension .py to indicate that it is a Python program. So, we’ll need to create that file either on our computers or in Codio or another tool if we are using one. For example, in Codio we can create the file in the python folder by right-clicking on it and selecting the New File option. We’ll name the file

New File New File

Once we’ve created that file, we can then open it by clicking on it. In Codio and in other online tools, it will open in the built-in editor. On a computer, we’ll need to open it in a text editor specifically designed for programming. We recommend Visual Studio Code , which is available on all platforms. Tools like the built-in Notepad tool on Windows, or a word processor like Word or Pages do not work for this task.

In that file, we’ll simply place the code shown above, like this:

Code Code

That’s all there is to it!

Running a Python Program

Once we’ve written the code, we can open the Terminal and navigate to where the code is stored in order to run the program. On Codio, we’ll just use the cd python command to enter the python directory. On a computer, we’ll need to navigate the file system to find the location where we placed our code. We highly recommend creating a folder directly within the home directory and placing all of our code there - that will make it easy to find!

Once we are in the correct directory, we can use the ls command to see the contents of that directory. If we see our file, we are in the correct location:

Show Python File Show Python File

If we don’t see our file, we should make sure we’ve saved it and that our current working directory is the same location as where the file is stored.

Finally, we can execute the file in Python using the python3 command, followed by the name of the file:


If everything works correctly, we should see output similar to this:

Hello World Output Hello World Output

There we go! We’ve just run our first program in Python! That’s a great first step to take.

Of course, there are lots of ways that this could go wrong. So, if you run into any issues getting this to work, please take the time to contact an instructor and ask for assistance. This process can be daunting the first time, since there are so many things to learn and so many intricacies we simply don’t have time to cover up front. Don’t be afraid to ask for help!

Subsections of Print Statement

Using Print

YouTube Video


One important key to remember: by default, the print(expression) statement in Python will add a newline to the end of the output by default. This means that multiple print(expression) statements will print on multiple lines. Let’s look at some examples!

Throughout this course, we’ll show many different code examples and their output here in the lab. To test them out, feel free to copy the code examples to a Python file and run it yourself. You can even tweak them to do something new and see how Python interprets different pieces of code. In the end, the best way to learn programming is to explore, and running these examples on your own is a great way to get started!

Example 1 - Multiple Statements

First, let’s write a simple program that prints 4 letters separated by spaces:

print("a b c d")

Just like our “Hello World” program, when we run this program, we’ll see that string printed in the user interface:

a b c d

Ok, that makes sense based on what we’ve previously seen. The print(expression) statement will simply display any string expression in our user interface.

Of course, programs can consist of multiple statements or lines of code. So, what if we write a program that contains multiple print(expression) statements, like this one:


What do you think will happen when we try to execute this program on our “mental model?” Have we learned a rule that tells us what should happen yet? Recall on the previous page we learned that it will print the value on the user interface, but that’s it. So, when we execute this program, we’ll see the following output:


That’s a very interesting result! We can see that four separate print(expression) statements will generate four lines of output by default. Each statement is printed on its own line. So, in Python we can print multiple lines of output simply by using multiple print(expression) statements!

Example 2 - Multiple Lines from Single Statement

What if we want to print output on multiple lines using a single print(expression) statement? How can we do that? In this case, we need to introduce a special symbol, the newline symbol. In most programming languages, the newline symbol is represented by a backslash followed by the letter “n”, like \n, in a string. When our user interface sees a newline symbol, it will move to the next line before printing the rest of the string. The newline symbol itself won’t appear in our output.

For example, we can update our previous program to contain newline symbols between each letter:


This might be a bit difficult to read at first, but as we become more and more familiar with reading code, we’ll start to see special symbols like the newline symbol just like any other letter. For now, we’ll just have to read closely and make sure we are on the lookout for special symbols in our text.

When we run this program, we should see the following output on our user interface:


There we go! We’ve now figured out how to print text on multiple lines using a single print(expression) statement.

Example 3 - Multiple Statements on Same Line

What if we want to display multiple print(expression) statements on the same line? To do that, we must add an additional option to the print(expression) statement - the end option.

For example, the following code will produce output all on the same line:

print("Hello ", end="")

In this example, we set end to be an empty string "". When we run this program, we’ll get the following output:

Hello World!

In fact, in Python, the print(expression) statement is an example of a function in Python. Functions are just repeatable procedures in our code - when we use them, we write the name of the function, followed by a set of parentheses and then inputs, or “arguments,” separated by commas within the parentheses. This is known as “calling” a function. So, in actuality, the expression in the print(expression) statement is just the first argument when we call the print function.

Therefore, the end option that we showed above is just a second argument that is optional - it simply lets us choose what to put at the end of the output. By default, the end parameter is set to the newline symbol \n, so if we don’t provide an argument for end it will just add a newline at the end of the value.

We can set the value of end to be any string. If we want to include a space at the end of the output, we can add end=" " to the print function call.

In this course, we won’t spend much time talking about optional parameters and default values in Python functions, but it is important to understand that statements like print are actually just Python functions behind the scenes!

Subsections of Using Print

Print Practice

Let’s try some simple practice problems. These problems are not graded - they are just for you to practice before doing the real exercises in the lab itself. You can find the answers below each question by clicking the button below each question.

1.1 Reading Code

What is the output that is displayed to the user after running the following Python code:

print("Kansas State University")
print("Manhattan ", end="")
print("KS", end=" ")
print("KSU!\nGo Cats!")
1.1 Answer

The correct output:

Kansas State University
Manhattan KS 66506
Go Cats!

1.2 Constructing Code

We want to write a program that produces the following output:

* *
* * *

Rearrange the following Python statements to create a program that produces that output. You may not use all of these statements in your answer.

print("*", end=" ")
print("*", end=" ")
print("*", end=" ")
1.2 Answer

One solution:

print("*", end=" ")
print("*", end=" ")
print("*", end=" ")

1.3 Writing Code

Write a Python program that will display the last five letters of the alphabet, one per line.

1.3 Answer

One possible answer is shown below:


Many others are possible!


YouTube Video


Now that we’ve learned how to use the print(expression) statement, let’s focus on the next major concept in Python, as well as any other programming language: variables.

The word variable is traditionally defined as a value that can change. We’ve seen variables like $ x $ used in Algebraic equations like $ x + 4 = 7 $ to represent unknown values that we can try to work out. In programming a variable is defined as a way to store a value in a computer’s memory so we can retrieve it later. One common way to think of variables is like a box in the real world. We can put something in the box, representing our value. Likewise, we can write a name on the side of the box, corresponding to our variable’s name. When we want to use the variable, we can get the value that it currently stores, and even change it to a different value. It’s a pretty handy mental metaphor to keep in mind!

In a later lab, we’ll learn how to use operators to manipulate the values stored in variables, but for right now we’re just going to focus on storing and retrieving data using variables.

Creating Variables

To use a variable, we must first create one. In Python, we create a variable in a special type of statement called an assignment statement. The basic structure for an assignment statement is a = expression. When our Python interpreter runs this statement, it will first evaluate expression into a single value. Then, it will store that value in the variable named a.

For example, let’s consider the Python statement:

x = "Hello World"

In that statement, we are storing the string value "Hello World" in the variable named x. Pretty handy!

Now, let’s cover some important rules related to assignment statements:

  1. Assignment statements are always written with the variable on the left, and an expression on the right. We cannot reverse the statement and say expression = x in programming like we can in math. In mathematical terms, this means an assignment statement is not commutative.
  2. The left side of an assignment statement must be a location where a value can be stored. For now, we’re just going to work with single variables, so we don’t have to worry about this yet. In a later lab, we’ll introduce lists as another way to store data, and we’ll revisit this rule.
  3. The right side of an assignment statement must be an expression that evaluates to a value that can be stored in the location given on the left side. Right now we’re only working with string values, so we don’t have to worry about this rule yet. We’ll come back to it in a future lab.

Using Variables

Once we’ve created a variable, we can use it in any expression to recall the current value stored in the variable. So, we can extend our previous example to store a value in a variable, and then use the print(expression) statement to display it’s value. Here’s what that would look like in Python:

x = "Hello World"

Notice that we don’t put quotation marks " around the variable x in the print(expression) statement. This is because we want to display the value stored in the variable x, not the string value "x". So, when we run this code, we should get this output:

Hello World

To confirm, feel free to try it yourself! Copy the code above into a Python file, then use the python3 command in the terminal to run the file and see what it does. Running these examples is a great way to learn how a computer actually executes code, and it helps to confirm that your “mental model” of a computer matches how a real computer operates.

Updating Variable Values

Python also allows us to change the value stored in a variable using another assignment statement. For example, we can write some Python code that uses the same variable to print multiple outputs:

a = "Output 1"
a = "Output 2"

When we run this code, we’ll see the following output:

Output 1
Ouptut 2

So, just like we learned above, when we evaluate a variable in code, it will result in the value currently stored in that variable at the time it is evaluated. So, even though we are printing the same variable twice, each time it is storing a different value. Recall that this is why we call items like a a variable - their value can change!

Variable Names

Finally, Python has a few simple rules that determine what names can be used for variables in our code. Let’s quickly review those rules, as well as some conventions that most Python developers follow when naming variables.

First, the rules that must be followed:

  1. Variable names must begin with either a letter or an underscore _.
  2. Variable names may only contain letters, numbers, and underscores _.
  3. Variable names are case sensitive.

Next, here are the conventions that most Python developers follow for variable names, which we will also follow in this course:

  1. Variable names beginning with an underscore _ have a special meaning. So, we won’t create any variables beginning with an underscore right now, but later we’ll learn about what they mean and start using them.
  2. Variables should have a descriptive name, like total or average, that makes it clear what the variable is used for.
  3. Variables should be named using Snake Case . This means that spaces are represented by underscores _, as in number_of_inputs
  4. Try to use traditional variable names only for their specific uses. Some examples of traditional variable names:
    1. tmp or temp are temporary variables.
    2. i, j, and k are iterator variables (we’ll learn about those later).
    3. x, y, and z are coordinates in a coordinate plane.
    4. r, g, b, a are colors in an RGB color system.
  5. Variables should not have the same name as keywords or any built-in statements or expressions in the language.
    1. For example, Python has a print statement, so we should not name a variable print in our language.
  6. In general, longer variable names are more useful than short ones, even if they are more difficult to type.

These conventions are not strict requirements enforced by the Python language itself, but they are general rules to help us write code that is meaningful and easy to read.

Finally, don’t forget that some of the code examples in this course will NOT follow these conventions, mainly because long, descriptive variable names might give away the purpose of the code itself. We’ll still follow the rules that are required, but in many cases we’ll use simple variable names so that the focus is learning to read the structure of the code, not inferring what it does based solely on the names of the variables.

Subsections of Variables

Code Tracing

YouTube Video


As we learn to write more complex programs in Python, it is important to make sure we can still mentally execute the code we are writing in our “mental model” of a computer before we actually run it on a computer. After all, if we don’t have at least an idea of what the code actually does before we write it, we really haven’t learned much about programming!

Thankfully, when working in a real programming language such as Python, there are many tools to help us visualize how the code works when we run it. This helps us continue to develop our “mental model” of a computer by looking behind the scenes a bit to see what is happening when we run our code.

One such tool is Python Tutor , a website that can quickly run short pieces of Python code to help us visualize what each line does and how it works. This tool is also integrated directly into Codio!

Python Tutor Example

Let’s look at an example of how Python Tutor compares to the manual code traces we performed in a previous lab. For this example, we’re going to use the following code:

x = "Hello"
y = x
print(y, end=" ")
x = "World"
print(x, end=", ")

This visualization can be found by clicking this Python Tutor Link to open Python Tutor on the web.

Stepping Through Code

The initial setup for Python Tutor is shown in the image below:

Python Tutor 1 Python Tutor 1

This looks similar to the setup we used when performing code tracing with pseudocode. We have an arrow next to our code that is keeping track of the next line to be executed, and we have areas to the side to record variables and outputs. In Python Tutor, the variables are stored in the Frames section. We’ll learn why that is important later in this lab when we start looking at Python functions.

So, let’s click the Next > button once to execute the first line of code. After we do that, we should see the following setup in Python Tutor:

Python Tutor 2 Python Tutor 2

That line is an assignment statement, so Python Tutor added an entry in the Frames section for the variable x, showing that it now contains the string value "Hello". It placed that variable in a frame it is calling the “Global frame,” which simply contains variables that are created outside of a function in Python.

When we click the Next > button again, we should see this:

Python Tutor 3 Python Tutor 3

Once again, the line that was just executed is an assignment statement, so Python Tutor will add a new variable entry for y to the list of variables. It will also store the string value "Hello". Just like before, notice that the variable y is storing the same value as x, but it is a copy of that value. The variables are not connected in any other way.

We can click Next > again to execute the next line of code:

Python Tutor 4 Python Tutor 4

Once this line is executed, we’ll see that it prints the value of the variable y to the output. Python Tutor will look up the value of y in the Frames section and print it in the output, but it won’t evaluate the expression in the code like we did when we performed code tracing in pseudocode. It’s a subtle difference, but it is worth noting.

Once again, we can click Next > to execute the next assignment statement:

Python Tutor 5 Python Tutor 5

This statement will update the value stored in the variable x to be the string value "World". After that, we can run the next statement:

Python Tutor 6 Python Tutor 6

That statement prints the value of x to the output, followed by a comma , and a space as shown in the end argument provided to the print function. Finally, we can click Next > one more time to execute the last line of code:

Python Tutor 7 Python Tutor 7

This will print the value of y to the output. Once the entire program has been executed, we should see the output Hello World, Hello printed to the screen.

The full process is shown in the animation below:

Python Tutor Python Tutor

Using tools like Python Tutor to step through small pieces of code and understand how the computer interprets them is a very helpful way to make sure our “mental model” of a computer accurately reflects what is going on behind the scenes when we run a piece of Python code on a real computer. So, as we continue to show and discuss examples in this course, feel free to use tools such as Python Tutor, as well as just running the code yourself, as a great way to make sure you understand what the code is actually doing.

Subsections of Code Tracing

Variables Practice

Let’s try some simple practice problems. These problems are not graded - they are just for you to practice before doing the real exercises in the lab itself. You can find the answers below each question by clicking the button below each question.

1.4 Reading Code

Write the output that is displayed to the user after running the following Python code:

a = "two"
b = a
c = a
print(c, end=" ")
c = "one"
b = c
a = "three"
print(a, end=" ")
1.4 Answer

The correct answer is:

two three one

1.5 Constructing Code

We want to write a program that produces the following output:

and a 1
and a 2
and a 3

Rearrange the following Python statements to create a program that produces that output. You may not use all of these statements in your answer.

x = "1"
x = "2"
x = "3"
print("and a", end=" ")
print("and a", end=" ")
print("and a", end=" ")
1.5 Answer

One possible answer is given below:

x = "1"
print("and a", end=" ")
x = "2"
print("and a", end=" ")
x = "3"
print("and a", end=" ")

1.6 Writing Code

We wish to write a Python program that displays the following output:

abba banana bandana

We currently have the following code:

a = "abba"
b = "banana"
c = "bandana"

# more code goes here

print(c, end=" ")
print(b, end=" ")

Complete the Python program by writing code where the # more code goes here comment is found so that the desired output is produced. See if you can do it by only using assignment statements and variables, without using any new string values. (Hint: you’ll need to create a least one new variable!)

1.6 Answer

One possible answer is given below:

a = "abba"
b = "banana"
c = "bandana"

# more code goes here
temp = a
a = c
c = temp

print(c, end=" ")
print(b, end=" ")

This problem demonstrates the typical process for swapping variables!



We introduced some basic statements and structures in the Python programming language. Let’s quickly review them!

The print(expression) statement is used to print output on the terminal.

  1. It will evaluate expression to a value, then display it to the screen.
  2. By default, it will add a newline to the end of the output.
  3. We can change that using the end parameter, such as print(expression, end="") to remove the newline.

Assignment Statement

The assignment statement, like a = expression is used to create variables and store values in the variables.

  1. The variable must be on the left side, and the right side must be an expression that evaluates to a single value.
  2. If the variable does not exist, it is created. Otherwise, the current value of the variable is replaced by the new value.
  3. Variable names must begin with a letter or underscore, and may only contain letters, numbers, and underscores.
  4. Variable names beginning with an underscore have a special meaning, so we won’t use them right now.