In this chapter, we'll show you how to run Python code. We'll also describe some basic Python coding conventions and briefly discuss Python packages. Finally, we'll look at a basic debugging technique. None of this information is exhaustive, but it should help you get through the rest of the book.
There are two main ways to run Python code with the python
command:
python
to execute code one line at a time. This mode is most helpful in determining what built-in functions and methods will do under different circumstances.
python
command to run the code from a file on your disk. This is the most common way to run Python code.
Note that we will be showing you some Python code in this chapter without thoroughly explaining what the code does. What's important in this chapter is learning how to use Python, whether it's using a REPL or running a Python program from a file. We'll also briefly talk about indentation, continuations, and using the print
function.
Before we begin doing anything with Python -- even running some trivial code -- we need to talk about indentation. Python is unusual among programming languages; it uses indentation to understand your code.
Most programming languages have little care about indentation. While most programmers indent their code carefully, this choice primarily concerns readability. Simple carelessness, though, often leads to code that is inconsistently or improperly indented. However, the language interpreter or compiler doesn't care about indentation. The code still works, no matter how it's indented. For instance, in the JavaScript language, you'll encounter code like this:
function doubleArray(array) {
// some code here
for (let index = 0; index < array.length; index += 1) {
// some more code here
array[index] = 2 * array[index];
}
}
Everything is neatly indented to show the structure of the code. The main program is flush against the left margin, the function body is indented by two spaces, and the body of the for
loop is indented by another two spaces. However, JavaScript doesn't care. The following code is equally valid but less readable:
function doubleArray(array) {
// some code here
for (let index = 0; index < array.length; index += 1) {
// some more code here
array[index] = 2 * array[index];
}
}
This code is also perfectly acceptable to JavaScript:
function doubleArray(array) {
// some code here
for (let index = 0; index < array.length; index += 1) {
// some more code here
array[index] = 2 * array[index];
}
}
Python is different. The code must be indented and indented consistently in any given "block" of code. For instance, the Python equivalent of the above code looks like this:
def double_list(input_list):
# some code here
for index, element in enumerate(input_list):
# some more code here
input_list[index] = 2 * element
The function definition (def
) is flush left. The function's body is indented by 4 spaces, and the body of the for
loop is indented another 4 spaces. If you try to rewrite that code without the indentation, Python will raise an error:
def double_list(input_list):
# some code here
for index, element in enumerate(input_list):
# some more code here
input_list[index] = 2 * element
# IndentationError: expected an indented block after
# function definition on line 1
Another thing to note: most languages delineate the beginning and end of the code inside multi-line statements like function definitions and loops. JavaScript and many other languages use the {
and }
characters to mark a block's beginning and end. Other languages use keywords like do
and end
to do the same thing. Python doesn't do this. Okay, it does use a :
to mark the beginning of a block of code, but the block ends only when the indentation is reduced:
def double_list(input_list):
for index, element in enumerate(input_list):
input_list[index] = element
return input_list
In this code, the return
statement is not part of the for
loop since its indentation is less than that of the loop's body. The indentation marks the beginning and end of the body of a multi-line statement.
If you've programmed in other languages, using indentation in Python may initially seem quirky. However, once you get used to it, you'll wonder why other languages do it differently.
Okay, let's learn how to use Python with these preliminaries out of the way.
Let's first discuss how to execute Python code line-by-line. We'll use Python's built-in REPL (Read-Eval-Print Loop). The REPL is an interactive environment where you type Python statements and expressions. You will see the results immediately. Python has a built-in REPL that's ideal for beginners exploring the language.
REPLs are programs that let you write and execute small snippets of code interactively. You can use Python's REPL to quickly try code to see what happens.
Python has several REPLs, but the most basic is the built-in REPL. The python
command invokes the built-in REPL when run without arguments. For instance:
$ python
Python 3.11.2
Type "help", "copyright", "credits" or "license" for more
information.
>>>
The last line (>>>
) is the REPL's prompt. You can enter a Python statement or expression after the prompt and see its output or return value, if any, below the prompt. It also distinguishes between what you type and the resulting output. You can enter as much Python code as you want, one at a time. Each time you enter a complete statement or expression, Python executes it and displays any output or return values produced.
As with shell commands that produce output, we disable the Copy Code functionality when depicting REPL sessions.
The REPL's prompt may vary depending on your system configuration, so it may look different on your computer. That's okay. Just ignore the leading >>>
when it appears in a code block. Do not type it. For example, in the following, you will type print('hello world!')
at the >>>
prompt, then press the Return or Enter key. The REPL will then display the output produced by print(...)
(hello world!
) followed by a new >>>
prompt.
>>> print('hello world!')
hello world!
>>>
You don't have to use print
explicitly if it's the last line entered. The REPL outputs the evaluated value of the last line of code to execute. In fact, this is a great way to perform quick mathematical calculations:
>>> 4 * 9 + 6
42
>>>
Multi-line statements, such as if
statements, can be tricky since you must remember to indent code properly and use colons (:
) where required. You also need to press the Return or Enter key once more to show that you are done typing. It looks like this:
>>> a = 42 # This is assignment; we'll discuss it later
>>> if a > 42:
... print('No')
... else:
... print('Yes')
...
Yes
>>>
Remember: indentation is important in Python.
Notice that the continuation lines in multi-line statements use ...
as a prompt. As with >>>
, the actual prompt may vary. You do not type the prompt, no matter what the prompt looks like.
You can also define and call functions in the REPL:
>>> def add_three(value):
... return value + 3
...
>>> add_three(39)
42
The help
function lets you request help in the Python REPL:
Display a short summary of how to use help
:
help()
Type q
and press {Return} to exit help
.
Display a short summary of how to use the len
function:
help(len)
Display a summary of the str
class:
help(str)
Display a summary of the bool
class by passing help
a Boolean value:
help(3 == 4)
help
is very flexible and will try to give you helpful information, no matter what value you pass it. You can't always predict how it might interpret some input, but it's reasonably good at guessing your intent.
To exit the REPL, type exit()
or quit()
followed by the Return or Enter key. Press the Control-D keyboard combination for an even easier way to close the REPL.
As of Python 3.13.0, you only have to type exit
or quit
; you may omit the parentheses.
Use the Up and Down arrow keys to navigate through your REPL history. You can use the Left and Right arrow keys to position the cursor and begin editing some prior input. (This may not work if your Python was built without the proper "readline" support.)
The REPL is a great way to experiment and learn with Python. You can quickly test out ideas, understand how functions behave, or even debug code snippets without the overhead of creating a full-fledged script.
Copying and pasting code into the Python REPL isn't reliable. In particular, if all 3 of the following statements are true, pasting into the REPL probably won't work:
You will probably get an indentation error on the line after the empty lines.
Unfortunately, there is no way to fix the copy and paste issue in Python prior to 3.13.0. However, there are at at least two workarounds:
Python 3.13.0 introduced a new feature in the REPL that makes pasting code work more reliably. To paste code cleanly in the REPL, first press the {F3}
key. This should change the prompt to (paste)
. You can now paste your code. When you are done pressing, press the {F3}
key again. You may need to press {Return}
to get back to the >>>
prompt.
Suppose you have a file named example.py
that contains some Python code you want to execute. For instance, assume the file contains the following code:
print('I wish to complain about this parrot.')
print("It's probably pining for the fjords!")
Once you've saved this file, you can run it as follows:
$ python example.py
I wish to complain about this parrot.
It's probably pining for the fjords!
Note that files with Python code typically have a .py
extension.
When you run a Python file from the command line, the Python compiler reads and converts the code into a form the computer understands. The compiled code is called byte code. Once the byte code is available, it gets passed to the interpreter, which executes the code. You don't need to know much about the compiler and interpreter except that you should recognize the terms.
One last tip: some Python programs may run for a long time, maybe infinitely. That may be intentional or due to a logic error. Regardless, you can use the Control-C keyboard combination to terminate such programs. Control-C sends an interrupt signal to the running program, which usually ends the program. For instance, try running the program in this endless_loop.py
file:
import time
while True:
time.sleep(1)
print(time.asctime())
Press the Control-C keyboard combination when you tire of watching the endless output.
The Python community has developed stylistic conventions that help make Python code easier to read and write. There are actually multiple conventions, and the different guidelines sometimes disagree. However, there's plenty of overlap in the recommendations.
Adhering to the style conventions of a programming language is helpful and meaningful even when you disagree with some recommendations. You probably won't be the sole person developing and maintaining a software project; sticking to a particular style convention helps your teammates and future maintainers understand your code. It's hard enough to understand code written by someone else; don't make it more challenging with unusual or non-standard stylistic choices.
The conventions discussed in this section are specific to the Python community. Other programming languages -- and even some Python sub-communities -- may have different preferences about each guideline.
Here's a short list of guidelines that we recommend. If you already work with a formal set of guidelines, please feel free to use them. If you don't, our suggestions should help you write readable code.
Set your text editor to use four space characters -- not tabs -- for indentation.
Set your text editor to expand tab characters to spaces.
Limit code lines and comments to 79 characters. This guideline isn't universal, but it helps readability. Not all developers have massive screens or good eyesight, so be kind and stick to this guideline.
Use spaces around operators, except for **
, which should not be surrounded by spaces:
print(3 + 4) # + is an operator
print(5 * 7) # * is an operator
print(6 - 2) # - is an operator
print(7 / 3) # / is an operator
print(8**3) # ** operator is not surrounded by spaces
my_num = 3 # = is an operator
print(3+4)
print(5* 7)
print(6 -2)
print(7/3)
print(8 ** 3) # Don't use spaces with **
my_num=3
Python uses the #
character as the beginning of a comment. Comments run through the end of the line.
# This line only has a comment
ultimate_answer = 42 # initializing variable
a_round_number = 3.141592 # another initialization
Programmers use comments to leave notes for other programmers or themselves at a later point in time. However, don't overdo your comments. Let your code do the talking instead.
Some Python language features use code blocks -- one or more lines of code that are treated as a unit. The statement introducing a block of code ends with a :
. In contrast, the block is indented with 4 spaces. The block ends when you outdent back to the original level.
if is_ok():
print('first thing')
print('another thing')
print('yet another thing')
print('This is not part of the above block')
if is_something():
print('do something')
print('do another thing')
else:
print('do something else')
while try_again():
print('first thing')
print('another thing')
print('yet another thing')
print('The loop has ended.')
You can also have multiple levels of indentation, though you should avoid using more than two levels:
if value <= 10:
print('value <= 10')
if value >= 5:
print('value >= 5')
else:
print('value < 5')
else:
print('value > 10')
Use spaces between operators and operands to make your code less cluttered and easier to read:
sum=x+5 # bad
sum = x + 5 # good
The previous section covers the essential style conventions you need to get started. If you want more information about Python styling, we recommend the Style Guide for Python Code, otherwise known as PEP 8. Check it out, but don't try to memorize all of the rules right away.
PEP stands for Python Enhancement Proposal. PEPs are numbered design documents that provide information and recommendations to the Python community, information about new or proposed language features, and standards and conventions.
PEP 8 is perhaps the best-known and most widely used PEP. It is the basis for most Python style conventions and should be reviewed occasionally by Python developers.
If you checked out PEP8, you may have noticed that one of the stylistic conventions in Python is that code lines should be no more than 79 characters in length. That means that you need to learn how to continue code over multiple lines. This can get a little tricky, but there are several ways to continue code over multiple lines:
String literals can be continued over several lines, provided you enclose all the string content in a set of parentheses:
return ("This is a long string. "
"It's actually very long. "
"It spans multiple lines. "
"Are you getting tired of this? "
"So am I.")
This also works with f-strings and r-strings, which we'll encounter later.
Sometimes, a triple quoted string is easier to deal with:
return """
This is a long string.
It's actually very long.
It spans multiple lines.
Are you getting tired of this?
So am I.
"""
It's worth noting that triple-quoted strings preserve leading whitespace and any newline characters. You also don't need parentheses.
Multi-value literals, such as lists and tuples, can be written over several lines by just using line-breaks between the brackets, braces, or parentheses used by the literal:
my_list = [
"Antonina",
"Brandi",
"Trevor",
]
my_tuple = (
3.141592,
2.718282,
1.414213,
)
my_set = {
"Dog",
"Cat",
"Pet",
}
When writing collection literals over multiple lines like this, the convention is to end every item in the list with a comma, including the last element. This convention makes it easy to add new elements to the end of the collection, and also permits easy sorting and rearranging.
You can use parentheses to delimit code that will be split over multiple lines:
return (obj.bar1
+ obj.bar2
+ obj.bar3)
You can use a backslash to end any line you want to continue:
result = value1 + \
value2 + \
value3
A good rule of thumb is that you can use a backslash wherever you can put a space.
That said, you should use backslash continuations sparingly, and only where they improve readability. You should not use backslashes when they aren't syntactically required for continuation. It's usually better to use one of the other continuation techniques.
The trickiest part of using continuations is often how to indent the continuation lines, especially when using if
and while
statements and comprehensions. The only rule we can offer is to aim for readability and consistency. The continued code should clearly be connected to the first line, and shouldn't blend into any following code blocks. We'll show some readable examples in this book and the Core curriculum.
JupyterLab and Jupyter Notebook are alternatives to the standard Python REPL. Both can also operate as a complete Python program editor and documentation generator. Jupyter offers many advantages over using the built-in REPL. The most significant benefits may be that you can write and try it out, copy and paste code from Launch School materials and elsewhere, and much more. The copy-and-paste functionality is especially handy as the built-in Python REPL badly mishandles blank lines in indented code when pasting. The built-in REPL is effectively unusable when you want to copy and paste code that has blank lines in indented code.
The easiest way to use Jupyter is to use one of the experimental browser-based versions of JupyterLab and Jupyter Notebook at the Try Jupyter page. You don't have to install anything -- not even Python. All you need is your browser. However, you won't have any control over what version of Python you are using. To see what version of Python is currently being used by one of these experimental programs, run the following code in a notebook:
import platform
platform.python_version()
If you would rather install your own version of Jupyter, you can do so on Macs, Windows (WSL2 preferred), and most Linux systems. Note that we don't recommend installing Jupyter on AWS Cloud9; the process is currently too complicated. It doesn't play well with Cloud9's "Preview" browser.
Recent versions of Linux Operating Systems (including the WSL2 version of Ubuntu) are starting to implement a security measure that prevents installing packages on top of a system-controlled version of Python. That means that installing Jupyter will fail on these systems. Later, in PY101, we'll show you how to set up a virtual environment that will let you install Jupyter on these systems. You can skip the rest of this section unless you are using a Macintosh with Homebrew.
On Mac systems, you can easily install JupyterLab with Homebrew:
brew install jupyterlab
Once installed, you can start Jupyter with one of these commands:
jupyter lab
jupyter notebook
The program will open in your browser, after which you can create a new notebook and write some code. When you want to execute the code, press {Shift}{Enter}.
Please note that we cannot support using, configuring, and troubleshooting JupyterLab and Jupyter Notebook. However, both products are widely used in the Python community. Help should be widely available, starting with the Jupyter website and the Jupyter community forums.
Python has a nifty built-in module called Pdb that lets you step through programs to see what happens on each line of code. This is a fantastic way to debug programs. However, before using Pdb to debug a program, you must learn how to use it. Now isn't the time to do that. We'll learn how to use Pdb later in the Core Curriculum.
For now, the easiest way to debug Python programs is to add print
statements at strategic points in your program. These print
statements can help quickly identify where and why your program isn't working.
Suppose we are writing a program that displays the maximum numeric value from a list of numeric strings:
max = '0'
for number in ['10', '2', '34', '6', '25']:
if number > max:
max = number
print('max value is', max)
Some of you may already see the problem, but not everyone will. Let's walk through using print
to debug this code.
First, let's run the code:
$ python compute_max.py
max value is 6
This answer isn't correct - the maximum numeric value should be 34
, not 6
. Let's use print
to try to diagnose the problem. There are two crucial values we need to see what is happening, max
and number
, so we'll print both values during each iteration of the loop:
max = '0'
for number in ['10', '2', '34', '6', '25']:
# highlight
print('max =', max, 'number =', number)
# endhighlight
if number > max:
max = number
print('max value is', max)
$ python compute_max.py
max = 0 number = 10
max = 10 number = 2
max = 2 number = 34
max = 34 number = 6
max = 6 number = 25
max value is 6
This output shows that max
was 0
and number
was 10
on the first iteration. (Remember, though, that these values are strings.) On the second iteration, max
was 10
and number
was 2
. This seems reasonable: 10 > 0
, so max
gets set to 10
. However, on the 3rd iteration, we see that max
is 2
. That can't be right: 2 < 10
, so max
should still be equal to 10
.
Let's display the value of number > max
to get a better idea of what's happening:
max = '0'
for number in ['10', '2', '34', '6', '25']:
# highlight
print('max =', max, 'number =', number,
'number > max =', number > max)
# endhighlight
if number > max:
max = number
print('max value is', max)
$ python compute_max.py
max = 0 number = 10 number > max = True
max = 10 number = 2 number > max = True
max = 2 number = 34 number > max = True
max = 34 number = 6 number > max = True
max = 6 number = 25 number > max = False
max value is 6
Hmm. It looks like the comparison is always True
except when we check 6
against 25
. This is a huge clue. It tells us we're comparing number
and max
as strings, not numbers. Strings are compared lexicographically, e.g., character by character, so '25' < '6'
while '6' > '34'
. That's because '2' < '6'
and '6' > '3'
. To fix this program, we must compare the values numerically. We can do this by converting the strings to integers when comparing them.
max = '0'
for number in ['10', '2', '34', '6', '25']:
print('max =', max, 'number =', number,
'number > max =', number > max)
# highlight
if int(number) > int(max):
# endhighlight
max = number
print('max value is', max)
$ python compute_max.py
max = 0 number = 10 number > max = True
max = 10 number = 2 number > max = True
max = 10 number = 34 number > max = True
max = 34 number = 6 number > max = True
max = 34 number = 25 number > max = False
max value is 34
Now we're getting the correct answer: 34
is the largest numeric value in the list.
Before we leave this problem, let's go ahead and delete the debugging code (the print
statement) and run the program one last time:
max = '0'
for number in ['10', '2', '34', '6', '25']:
# print statement deleted
if int(number) > int(max):
max = number
print('max value is', max)
$ python compute_max.py
max value is 34
It's worth your time to learn to use this debugging technique. In particular, you may need it in Coderpad, which we use for interview assessments. Coderpad does not support debugging tools, so print
is the only way to go.
A question that comes up often with our exercises is "My answer is different from Launch School's, but it still works. What should I do?"
Even with simple problems, there are often several different ways to solve an exercise, and sometimes many different ways. At this stage in your journey, the important part is to understand what you’ve read and be able to use that knowledge to answer questions, even if your answer is a little different. Once you're satisfied with your answer, you want to check it against Launch School's answer. Your answer doesn't have to be the same as ours. In fact, having an alternative answer affords you the opportunity to learn from seeing a different approach. How is your solution different from Launch School's? Do you understand our solution too?
Of course, you should be sure to check that your answer satisfies the requirements of the exercise. Does the output match the expected output, exactly? Does it properly handle any edge cases that may be mentioned? Sometimes, an answer may seem like it's correct, but you may have missed one of the requirements.
As long as you understand both your solution and ours, feel free to move on to the next exercise. At this point, you’re building up an awareness of the language, functions, methods, and all the different ways you can do things. Having a different answer is not bad or a sign that you need to go back.
Create a directory named my_folder
and navigate to that directory. Create two files named one.py
and two.py
in my_folder
. Add the following Python code to one.py
:
print('This is file one')
Write a similar program in two.py
that prints This is file two
.
When finished, run both programs with the python
command.
$ mkdir my_folder
$ cd my_folder
$ touch one.py
$ touch two.py
# Use your editor to edit one.py and two.py
$ python one.py
This is file one
$ python two.py
This is file two
Video Walkthrough
When you finish Exercise 1, navigate to the directory above the my_folder
directory and delete all the content you generated in Exercise 1 with one command.
WARNING: The rm
command is DANGEROUS. You can't undo this command. The effects are permanent. Ensure you are in the correct directory and are using the right name of the directory you want to delete. Check three times!
$ cd ..
$ pwd # Use to check where you are
$ ls # Use to verify my_folder exists
$ rm -R my_folder
To repeat, use extreme caution when using the rm
command. It's destructive and irreversibly deletes folders and files. That's why we use pwd
and ls
to ensure what we're about to do is being done where it should be done.
Video Walkthrough