Python Basics Sample Chapters
Python Basics Sample Chapters
to Python 3
Real Python
Python Basics: A Practical Introduction to Python 3
For online information and ordering of this and other books by Real
Python, please visit realpython.com. For more information, please
contact us at [email protected].
Thank you for downloading this ebook. This ebook is licensed for your
personal enjoyment only. This ebook may not be resold or given away
to other people. If you would like to share this book with another per-
son, please purchase an additional copy for each recipient. If you’re
reading this book and did not purchase it, or if it was not purchased for
your use only, then please return to realpython.com/pybasics-book
and purchase your own copy. Thank you for respecting the hard work
behind this book.
This is a sample from “Python Basics: A Practical
Introduction to Python 3”
With the full version of the book you get a complete Python curriculum
to go all the way from beginner to intermediate-level. Every step along
the way is explained and illustrated with short & clear code samples.
Coding exercises within each chapter and our interactive quizzes help
fast-track your progress and ensure you always know what to focus on
next.
— Thomas Wong
“Three years later and I still return to my Real Python books when I
need a quick refresher on usage of vital Python commands.”
— Rob Fowler
— Jared Nielsen
“I love the book because at the end of each particular lesson there are
real world and interesting challenges. I just built a savings estimator
that actually re ects my savings account – neat!”
— Drew Prescott
“As a practice of what you taught I started building simple scripts for
people on my team to help them in their everyday duties. When my
managers noticed that, I was o ered a new position as a developer.
I know there is heaps of things to learn and there will be huge chal-
lenges, but I nally started doing what I really came to like.
— Kamil
“What I found great about the Real Python courses compared to others
is how they explain things in the simplest way possible.
— Stephen Grady
“After reading the rst Real Python course I wrote a script to automate
a mundane task at work. What used to take me three to ve hours now
takes less than ten minutes!”
— Brandon Youngdale
“Honestly, throughout this whole process what I found was just me
looking really hard for things that could maybe be added or improved,
but this tutorial is amazing! You do a wonderful job of explaining and
teaching Python in a way that people like me, a complete novice, could
really grasp.
— Shea Klusewicz
I really liked that there was always full code examples and each line
of code had good comments so you can see what is doing what.
I now have a number of books on Python and the Real Python ones
are the only ones I have actually nished cover to cover, and they
are hands down the best on the market. If like me, you’re not a pro-
grammer (I work in online marketing) you’ll nd these courses to be
like a mentor due to the clear, u -free explanations! Highly recom-
mended!”
— Craig Addyman
About the Authors
At Real Python you’ll learn real-world programming skills from a com-
munity of professional Pythonistas from all around the world.
David Amos is the content technical lead for Real Python. After leav-
ing academia in 2015, David worked in various technical positions as
a programmer and data scientist. In 2019, David joined Real Python
full time to pursue his passion for education. He lead the charge on
rewriting and updating the Python Basics curriculum to Python 3.
Dan Bader is the owner and editor in chief of Real Python and the
main developer of the realpython.com learning platform. Dan has
been writing code for more than twenty years and holds a master’s
degree in computer science. He’s the author of Python Tricks, a best-
selling programming book for intermediate Python developers.
Contents 8
Foreword 13
1 Introduction 20
1.1 Why This Book? . . . . . . . . . . . . . . . . . . . . 21
1.2 About Real Python . . . . . . . . . . . . . . . . . . 23
1.3 How to Use This Book . . . . . . . . . . . . . . . . . 24
1.4 Bonus Material and Learning Resources . . . . . . . 25
2 Setting Up Python 29
2.1 A Note on Python Versions . . . . . . . . . . . . . . 30
2.2 Windows . . . . . . . . . . . . . . . . . . . . . . . 31
2.3 macOS . . . . . . . . . . . . . . . . . . . . . . . . . 34
2.4 Ubuntu Linux . . . . . . . . . . . . . . . . . . . . . 37
8
Contents
9
Contents
10
Contents
11
Contents
12
Foreword
If you don’t have a computer science degree, don’t worry. David, Dan,
Joanna, and Fletcher will guide you through the important comput-
ing concepts while teaching you the Python basics and, just as impor-
tantly, skipping the unnecessary details at first.
When learning a new programming language, you don’t yet have the
experience to judge how well it will serve you in the long run. If you’re
considering learning Python, let me assure you that this is a good
choice. One key reason is that Python is a full-spectrum language.
What do I mean by this? Some languages are very good for beginners.
They hold your hand and make programming super easy. We can go
to the extreme and look at visual languages such as Scratch.
13
Contents
ple programs, but you cannot build professional applications with it.
Name one Fortune 500 company that powers its core business logic
with Scratch.
You can do amazing things with these languages, but they are wholly
unwelcoming to newcomers looking for a gentle introduction.
You might not have read a lot of C++ code. It can almost make your
eyes burn. Here’s an example, a real albeit complex one:
Both Scratch and C++ are decidedly not what I would call full-
spectrum languages. With Scratch, it’s easy to start, but you have to
switch to a “real” language to build real applications. Conversely, you
can build real apps with C++, but there’s no gentle on-ramp. You
dive headfirst into all the complexity of the language, which exists to
support these rich applications.
14
Contents
print("Hello, World")
The Hello, World test is useful but really not enough to show the power
or complexity of a language. Let’s try another example. Not every-
thing here needs to make total sense—just follow along to get the Zen
of it. The book covers these concepts and more as you go through. The
next example is certainly something you could write as you get near
the end of the book.
Here’s the new test: What would it take to write a program that ac-
cesses an external website, downloads the content to your app in mem-
ory, then displays a subsection of that content to the user? Let’s try
that experiment using Python 3 with the help of the requests package
(which needs to be installed—more on that in chapter 12):
import requests
resp = requests.get("http://olympus.realpython.org")
html = resp.text
print(html[86:132])
Incredibly, that’s it! When run, the program outputs something like
this:
15
Contents
So there you have a simple yet powerful starter example. On the real-
world side of things, many incredible applications have been written
in Python as well.
This full-spectrum aspect of Python means that you can start with
the basics and adopt more advanced features as your application de-
mands grow.
Python Is Popular
You might have heard that Python is popular. It may seem that it
doesn’t really matter how popular a language is so long as you can
build the app you want to build with it.
So, is Python actually that popular? Yes it is. You’ll find a lot of
hype and hyperbole, but there are plenty of stats backing this claim.
Let’s look at some analytics presented by stackoverflow.com, a popu-
lar question-and-answer site for programmers.
Stack Overflow runs a site called Stack Overflow Trends where you can
look at the trends for various technologies by tag. When you compare
16
Contents
Python to the other likely candidates you could pick to learn program-
ming, you’ll see one is unlike the others:
You can explore this chart and create similar charts to this one over at
insights.stackoverflow.com/trends.
That’s just one chart—what does it really tell us? Well, let’s look at
another. Stack Overflow does a yearly survey of developers. It’s com-
prehensive and very well done. You can find the full 2020 results at
insights.stackoverflow.com/survey/2020.
From that writeup, I’d like to call your attention to a section titled
“Most Loved, Dreaded, and Wanted Languages.” In the “Most
Wanted” section, you’ll find data on the share of “developers who are
not developing with the language or technology but have expressed
interest in developing with it.”
17
Contents
Again, in the graph below, you’ll see that Python is topping the charts
and is well above even second place:
One other point that I want to emphasize as you start your Python
learning journey is that we don’t need you to be a computer scientist.
If that’s your goal, then great. Learning Python is a powerful step
in that direction. But the invitation to learn programming is often
framed as “We have all these developer jobs going unfilled! We need
software developers!”
To illustrate this idea, suppose you are a biologist. Should you drop
out of biology and get a job as a front-end web developer? Probably
not. But skills such as the one I opened this foreword with, using re-
quests to get data from the Web, can be incredibly powerful for you as
a biologist.
Rather than manually exporting and scraping data from the Web or
from spreadsheets, you can use Python to scrape thousands of data
sources or spreadsheets in the time it takes you to do just one man-
18
Contents
ually. Python skills can take your biology power and amplify it well
beyond your colleagues’ to make it your superpower.
Finally, let me leave you with a comment on your authors. Dan Bader
and the other Real Python authors work day in and day out to bring
clear and powerful explanations of Python concepts to all of us via
realpython.com.
They have a unique view into the Python ecosystem and are keyed into
what beginners need to know.
19
Chapter 1
Introduction
No matter what your ultimate goals may be, if you work with a com-
puter at all, then you’ll soon be finding endless ways to improve your
life by automating tasks and solving problems through Python pro-
grams that you create.
20
1.1. Why This Book?
#include <stdio.h>
int main(void)
{
printf("Hello, World\n");
}
All the program does is show the text Hello, World on the screen. That
was a lot of work to output one phrase! Here’s the same program writ-
ten in Python:
print("Hello, World")
That’s pretty simple, right? The Python code is faster to write and
easier to read. We find that it looks friendlier and more approachable,
too!
At the same time, Python has all the functionality of other languages
and more. You might be surprised by how many professional products
are built on Python code: Instagram, YouTube, Reddit, Spotify, to
name just a few.
Python is not only a friendly and fun language to learn, but it also pow-
ers the technology behind multiple world-class companies and offers
fantastic career opportunities for any programmer who masters it.
21
1.1. Why This Book?
You may be asking yourself, What should I learn about Python in the
beginning to get a strong foundation? If so, then this book is for you,
no matter if you’re a complete beginner or if you’ve already dabbled
in Python or other languages.
Python Basics is written in plain English and breaks down the core
concepts that you really need to know into bite-sized chunks. This
means you’ll learn enough to be dangerous with Python, fast.
Step by step, you’ll master fundamental Python concepts that will help
you get started on your journey toward learning Python.
This book is built on the 80/20 principle, which suggests that you can
learn most of what you need to know by focusing on a few crucial con-
cepts. We’ll cover the commands and techniques used in the vast ma-
jority of cases and focus on how to program real-world solutions to
everyday problems.
22
1.2. About Real Python
Once you’ve mastered the material in this book, you will have gained
a strong enough foundation that venturing out on your own into more
advanced territory will be a breeze.
What you’ll learn here is based on the first part of the original Real
Python Course initially released in 2012. Over the years, this Python
curriculum has been battle-tested by thousands of Pythonistas, data
scientists, and developers working for companies big and small, in-
cluding Amazon, Red Hat, and Microsoft.
• realpython.com
• @realpython on Twitter
• The Real Python Newsletter
• The Real Python Podcast
23
1.3. How to Use This Book
The practice files that accompany this book also include full solutions
to the challenges as well as some of the trickier exercises. But to get
the most out of the material, you should try your best to solve the chal-
lenge problems on your own before looking at the example solutions.
If you have any questions or feedback about the book, you’re always
welcome to contact us directly.
24
1.4. Bonus Material and Learning Resources
Learning by Doing
This book is all about learning by doing, so be sure to actually type
in the code snippets you encounter in the book. For best results, we
recommend that you avoid copying and pasting the code examples.
You’ll learn the concepts better and pick up the syntax faster if you
type out each line of code yourself. Plus, if you screw up—which is to-
tally normal and happens to all developers on a daily basis—the simple
act of correcting typos will help you learn how to debug your code.
Try to complete the review exercises and code challenges on your own
before getting help from outside resources. With enough practice,
you’ll master this material—and have fun along the way!
Take your time and don’t feel like you have to rush. Programming is a
super-rewarding but complex skill to learn. Good luck on your Python
journey. We’re rooting for you!
realpython.com/python-basics/resources
25
1.4. Bonus Material and Learning Resources
Interactive Quizzes
Most chapters in this book come with a free online quiz to check your
learning progress. You can access the quizzes using the links provided
at the end of the chapter. The quizzes are hosted on the Real Python
website and can be viewed on your phone or computer.
At the end of the quiz, you’ll receive a grade based on your result. If
you don’t score 100 percent on your first try, don’t fret! These quizzes
are meant to challenge you. It’s expected that you’ll go through them
several times, improving your score with each run.
realpython.com/python-basics/exercises
Note
The code found in this book has been tested with Python 3.9 on
Windows, macOS, and Linux.
26
1.4. Bonus Material and Learning Resources
Formatting Conventions
Code blocks will be used to present example code:
Note
This is a note filled in with placeholder text. The quick brown
fox jumps over the lazy dog. The quick brown Python slithers
over the lazy hog.
27
1.4. Bonus Material and Learning Resources
realpython.com/python-basics/feedback
28
Chapter 2
Setting Up Python
To get the most out of this book, you need a computer with Python
installed on it and a way to create, edit, and save Python code files.
29
2.1. A Note on Python Versions
The system Python is used by your operating system and is usually out
of date. It’s essential that you have the most recent version of Python
so that you can successfully follow along with the examples in this
book.
Important
Note
Even if you already have Python 3.9 installed, it’s still a good
idea to skim this chapter to double-check that your environ-
ment is set up for following along with this book.
If you have a different operating system, then check out Real Python’s
“Python 3 Installation & Setup Guide” to see if your OS is covered.
Readers on tablets and mobile devices can refer to the “Online Python
Interpreters” section for some browser-based options.
30
2.2. Windows
2.2 Windows
Follow these steps to install Python 3 and open IDLE on Windows.
Important
Install Python
Windows doesn’t typically come with a system Python. Fortunately,
installation involves little more than downloading and running the
Python installer from the Python.org website.
https://www.python.org/downloads/windows/
Then scroll to the bottom and click Windows x86-64 executable in-
staller to start the download.
Note
If your system has a 32-bit processor, then you should choose
the 32-bit installer. If you aren’t sure if your computer is 32-bit
or 64-bit, stick with the 64-bit installer mentioned above.
31
2.2. Windows
It’s okay if the Python version you see is greater than 3.9.0 as long as
the version is not less than 3.
Important
Make sure you select the box that says Add Python 3.x to PATH.
If you install Python without selecting this box, then you can
run the installer again and select it.
Click Install Now to install Python 3. Wait for the installation to finish,
then continue to open IDLE.
32
2.2. Windows
Open IDLE
You can open IDLE in two steps:
1. Click the Start menu and locate the Python 3.9 folder.
2. Open the folder and select IDLE (Python 3.9).
Note
While you’re free to use a code editor other than IDLE if you
prefer, note that some chapters, especially chapter 7, “Finding
and Fixing Code Bugs,” do contain material specific to IDLE.
At the top of the window, you can see the version of Python that is
running and some information about the operating system. If you see
a version less than 3.9, then you may need to revisit the installation
instructions in the previous section.
33
2.3. macOS
The >>> symbol that you see is called a prompt. Whenever you see
this, it means that Python is waiting for you to give it some instruc-
tions.
Interactive Quiz
This chapter comes with a free online quiz to check your learn-
ing progress. You can access the quiz using your phone or com-
puter at the following web address:
realpython.com/quizzes/pybasics-setup
Now that you have Python installed, let’s get straight into writing your
first Python program! Go ahead and move on to chapter 3.
2.3 macOS
Follow these steps to install Python 3 and open IDLE on macOS.
Important
Install Python
To install the latest version of Python 3 on macOS, download and run
the official installer from the Python.org website.
https://www.python.org/downloads/mac-osx/
34
2.3. macOS
Then scroll to the bottom of the page and click macOS 64-bit installer
to start the download.
Open Finder and double-click the downloaded file to run the installer.
A dialog box that looks like the following will appear:
Press Continue a few times until you are asked to agree to the software
license agreement. Then click Agree .
You’ll be shown a window that tells you where Python will be installed
and how much space it will take. You most likely don’t want to change
the default location, so go ahead and click Install to start the installa-
tion.
35
2.3. macOS
When the installer is finished copying files, click Close to close the
installer window.
Open IDLE
You can open IDLE in three steps:
Note
While you’re free to use a code editor other than IDLE if you
prefer, note that some chapters, especially chapter 7, “Finding
and Fixing Code Bugs,” do contain material specific to IDLE.
36
2.4. Ubuntu Linux
At the top of the window, you can see the version of Python that is
running and some information about the operating system. If you see
a version less than 3.9, then you may need to revisit the installation
instructions in the previous section.
The >>> symbol that you see is called a prompt. Whenever you see
this, it means that Python is waiting for you to give it some instruc-
tions.
Interactive Quiz
This chapter comes with a free online quiz to check your learn-
ing progress. You can access the quiz using your phone or com-
puter at the following web address:
realpython.com/quizzes/pybasics-setup
Now that you have Python installed, let’s get straight into writing your
first Python program! Go ahead and move on to chapter 3.
Important
37
2.4. Ubuntu Linux
Install Python
There’s a good chance that your Ubuntu distribution already has
Python installed, but it probably won’t be the latest version, and it
may be Python 2 instead of Python 3.
To find out what version(s) you have, open a terminal window and try
the following commands:
$ python --version
$ python3 --version
$ python3 --version
Python 3.9.0
Your version number may vary. If the version shown is Python 2.x
or a version of Python 3 that is less than 3.9, then you want to in-
stall the latest version. How you install Python on Ubuntu depends
on which version of Ubuntu you’re running. You can determine your
local Ubuntu version by running the following command:
$ lsb_release -a
No LSB modules are available.
Distributor ID: Ubuntu
Description: Ubuntu 18.04.1 LTS
Release: 18.04
Codename: bionic
Look at the version number next to Release in the console output, and
follow the corresponding instructions below.
38
2.4. Ubuntu Linux
Ubuntu version 18.04 does not come with Python 3.9 by default, but
it is in the Universe repository. You can install it with the following
commands in the Terminal application:
For Ubuntu versions 17 and lower, Python 3.9 is not in the Universe
repository. You need to get it from a Personal Package Archive (PPA).
To install Python from the deadsnakes PPA, run the following com-
mands in the Terminal application:
You can check that the correct version of Python was installed by run-
ning python3 --version. If you see a version number less than 3.9, then
you may need to type python3.9 --version. Now you can open IDLE
and get ready to write your first Python program.
Open IDLE
You can open IDLE from the command line by typing the following:
$ idle-python3.9
39
2.4. Ubuntu Linux
On some Linux installations, you can open IDLE with the following
shortened command:
$ idle3
Note
While you’re free to use a code editor other than IDLE if you
prefer, note that some chapters, especially chapter 7, “Finding
and Fixing Code Bugs,” do contain material specific to IDLE.
At the top of the window, you can see the version of Python that is
running and some information about the operating system. If you see
a version less than 3.9, then you may need to revisit the installation
instructions in the previous section.
40
2.4. Ubuntu Linux
Important
If you open IDLE with the idle3 command and see a version less
than 3.9 displayed in the Python shell window, then you’ll need
to open IDLE with the idle-python3.9 command.
The >>> symbol that you see in the IDLE window is called a prompt.
Whenever you see this, it means that Python is waiting for you to give
it some instructions.
Interactive Quiz
This chapter comes with a free online quiz to check your learn-
ing progress. You can access the quiz using your phone or com-
puter at the following web address:
realpython.com/quizzes/pybasics-setup
Now that you have Python installed, let’s get straight into writing your
first Python program! Go ahead and move on to chapter 3.
41
Chapter 3
Now that you have the latest version of Python installed on your com-
puter, it’s time to start coding!
42
3.1. Write a Python Program
You can type code into both the interactive window and the editor win-
dow. The difference between the two windows is in how they execute
code. In this section, you’ll learn how to execute Python code in both
windows.
This text shows the version of Python that IDLE is running. You
can also see information about your operating system and some
commands you can use to get help and view information about
Python.
The >>> symbol in the last line is called the prompt. This is where
you’ll type in your code.
43
3.1. Write a Python Program
>>> 1 + 1
2
>>>
Python evaluates the expression, displays the result (2), then displays
another prompt. Every time you run some code in the interactive win-
dow, a new prompt appears directly below the result.
At the prompt in the interactive window, type the word print followed
by a set of parentheses with the text "Hello, World" inside:
44
3.1. Write a Python Program
The parentheses tell Python to call the print() function. They also en-
close everything that gets sent to the function as input. The quotation
marks indicate that "Hello, World" really is text and not something
else.
Note
IDLE highlights parts of your code in different colors as you
type to make it easier for you to identify the different parts.
Alternatively, you can save Python code in a text file and execute all of
the code in the file to run an entire program.
The interactive window stays open when you open the editor window.
It displays the output generated by code in the editor window, so you’ll
want to arrange the two windows so that you can see them both at the
same time.
45
3.1. Write a Python Program
In the editor window, type in the same code you used to print "Hello,
World" in the interactive window:
print("Hello, World")
IDLE highlights code typed into the editor window just like in the in-
teractive window.
Important
When you write code in a Python file, you don’t need to include
the >>> prompt.
Before you run your program, you need to save it. Select File Save
from the menu and save the file as hello_world.py.
Note
On some systems, the default directory for saving files in IDLE
is the Python installation directory. Do not save your files to
this directory. Instead, save them to your desktop or to a folder
in your user’s home directory.
The .py extension indicates that a file contains Python code. In fact,
saving your file with any other extension removes the code highlight-
ing. IDLE only highlights Python code when it’s stored in a .py file.
To run your program, select Run Run Module from the menu in the
editor window.
Note
46
3.2. Mess Things Up
Every time you run code from a file, you’ll see something like the fol-
lowing output in the interactive window:
To open an existing file in IDLE, select File Open from the menu,
then select the file you want to open. IDLE opens every file in a new
editor window, so you can have several files open at the same time.
You can also open a file from a file manager, such as Windows
Explorer or macOS Finder. Right-click the file icon and select
Edit with IDLE to open the file in IDLE’s editor window.
For now, the best way to run your Python programs is to open them
in IDLE’s editor window and run them from there.
47
3.2. Mess Things Up
Syntax Errors
A syntax error occurs when you write code that isn’t allowed in the
Python language.
Let’s create a syntax error by removing the last quotation mark from
the code in the hello_world.py file that you created in the last section:
print("Hello, World)
Save the file and press F5 to run it. The code won’t run! IDLE dis-
plays an alert box with the following message:
So, the message tells you that Python got to the end of a line while
reading a string literal. String literals must be terminated with a quo-
tation mark before the end of a line.
Runtime Errors
IDLE catches syntax errors before a program starts running. In con-
trast, runtime errors only occur while a program is running.
48
3.2. Mess Things Up
print(Hello, World)
Did you notice how the text color changed to black when you removed
the quotation marks? IDLE no longer recognizes Hello, World as text.
What do you think will happen when you run the program? Press F5
to find out!
• The last line of the traceback tells you the name of the error and
the error message. In this case, a NameError occurred because the
name Hello is not defined anywhere.
• The second to last line shows you the code that produced the error.
There’s only one line of code in hello_world.py, so it’s not hard to
guess where the problem is. This information is more helpful for
larger files.
• The third to last line tells you the name of the file and the line num-
ber so you can go to the exact spot in your code where the error
occurred.
In the next section, you’ll see how to define names for values in your
code. Before you move on, though, you can get some practice with
syntax errors and runtime errors by working on the review exercises.
49
3.3. Create a Variable
Review Exercises
You can nd the solutions to these exercises and many other bonus
resources online at realpython.com/python-basics/resources
1. Write a program that IDLE won’t run because it has a syntax error.
2. Write a program that crashes only while it’s running because it has
a runtime error.
In this section, you’ll learn how to use variables in your code, as well as
some of the conventions Python programmers follow when choosing
names for variables.
50
3.3. Create a Variable
Let’s modify the hello_world.py file from the previous section to assign
some text in a variable before printing it to the screen:
On the first line, you create a variable named greeting and assign it the
value "Hello, World" using the = operator.
World", and replaces the variable name with its value before calling
the function.
Note
Although = looks like the equals sign from mathematics, it has a
different meaning in Python. This distinction is important and
can be a source of frustration for beginner programmers.
51
3.3. Create a Variable
• string1
• _a1p4a
• list_of_names
The following aren’t valid variable names because they start with a
digit:
• 9lives
• 99_balloons
• 2beOrNot2Be
52
3.3. Create a Variable
Note
You’ll learn more about Unicode in chapter 12.
You can also read about Python’s support for Unicode in the
official Python documentation.
s = 3600
The name s is totally ambiguous. Using a full word makes it a lot easier
to understand what the code means:
seconds = 3600
53
3.3. Create a Variable
The following name leaves no doubt about what the code means:
seconds_per_hour = 3600
When you read the above code, there’s no question that 3600 is the
number of seconds in an hour. seconds_per_hour takes longer to type
than both the single letter s and the word seconds, but the payoff in
clarity is massive.
54
3.4. Inspect Values in the Interactive Window
Note
PEP stands for Python Enhancement Proposal. A PEP is a de-
sign document used by the Python community to propose new
features to the language.
Review Exercises
You can nd the solutions to these exercises and many other bonus
resources online at realpython.com/python-basics/resources
When you press Enter after typing greeting a second time, Python
prints the string literal assigned to greeting even though you didn’t
use the print() function. This is called variable inspection.
55
3.4. Inspect Values in the Interactive Window
Now print the string assigned to greeting using the print() function:
>>> print(greeting)
Hello, World
Can you spot the difference between the output displayed by using
print() and the output displayed by just entering the variable name
and pressing Enter ?
When you type the variable name greeting and press Enter , Python
prints the value assigned to the variable as it appears in your code.
You assigned the string literal "Hello, World" to greeting, which is why
'Hello, World' is displayed with quotation marks.
Note
String literals can be created with single or double quotation
marks in Python. At Real Python, we use double quotes wher-
ever possible, whereas IDLE output appears in single quotes by
default.
Both "Hello, World" and 'Hello, World' mean the same thing in
Python—what’s most important is that you be consistent in your
usage. You’ll learn more about strings in chapter 4.
>>> x = 2
>>> x
2
>>> print(x)
2
56
3.4. Inspect Values in the Interactive Window
Here, you assign the number 2 to x. Both using print(x) and inspecting
x display output without quotation marks because 2 is a number and
not text. In most cases, though, variable inspection gives you more
useful information than print().
>>> x = 2
>>> y = "2"
>>> print(x)
2
>>> print(y)
2
>>> x
2
>>> y
'2'
The program executes without any errors, but it doesn’t display any
output!
57
3.5. Leave Yourself Helpful Notes
To help avoid this problem, you can leave comments in your code.
Comments are lines of text that don’t affect the way a program runs.
They document what code does or why the programmer made certain
decisions.
Comments that start on a new line are called block comments. You
can also write inline comments, which are comments that appear
on the same line as the code they reference. Just put a # at the end of
the line of code, followed by the text in your comment.
Of course, you can still use the # symbol inside a string. For instance,
Python won’t mistake the following for the start of a comment:
>>> print("#1")
#1
58
3.5. Leave Yourself Helpful Notes
You can also use comments to comment out code while you’re test-
ing a program. Putting a # at the beginning of a line of code lets you
run your program as if that line of code didn’t exist, but it doesn’t ac-
tually delete the code.
• Windows: Alt + 3
• macOS: Ctrl + 3
• Windows: Alt + 4
• macOS: Ctrl + 4
59
3.6. Summary and Additional Resources
Then you learned about syntax errors, which occur before IDLE ex-
ecutes a program that contains invalid Python code, and runtime
errors, which only occur while a program is running.
Finally, you learned how to write helpful comments in your code for
when you or someone else looks at it in the future.
60
3.6. Summary and Additional Resources
Interactive Quiz
This chapter comes with a free online quiz to check your learn-
ing progress. You can access the quiz using your phone or com-
puter at the following web address:
realpython.com/quizzes/pybasics-first-program
Additional Resources
To learn more, check out the following resources:
61
Chapter 4
62
4.1. What Is a String?
Note
There are several other data types built into Python. For exam-
ple, you’ll learn about numerical data types in chapter 5 and
Boolean data types in chapter 8.
We say that strings are a fundamental data type because they can’t
be broken down into smaller values of a different type. Not all data
types are fundamental. You’ll learn about compound data types, also
known as data structures, in chapter 9.
The string data type has a special abbreviated name in Python: str.
You can see this by using type(), which is a function used to determine
the data type of a given value.
The output <class 'str'> indicates that the value "Hello, World" is an
instance of the str data type. That is, "Hello, World" is a string.
63
4.1. What Is a String?
Note
For now, you can think of the word class as a synonym for data
type, although it actually refers to something more specific.
You’ll see just what a class is in chapter 10.
type() also works for values that have been assigned to a variable:
String Literals
As you’ve already seen, you can create a string by surrounding some
text with quotation marks:
You can use either single quotes (string1) or double quotes (string2)
to create a string as long as you use the same type at the beginning
and end of the string.
64
4.1. What Is a String?
Note
Not every string is a string literal. Sometimes strings are input
by a user or read from a file. Since they’re not typed out with
quotation marks in your code, they’re not string literals.
After Python reads the first delimiter, it considers all the characters
after it part of the string until it reaches a second matching delimiter.
This is why you can use a single quote in a string delimited by double
quotes, and vice versa.
Python throws a SyntaxError because it thinks the string ends after the
second ", and it doesn’t know how to interpret the rest of the line. If
you need to include a quotation mark that matches the delimiter in-
side a string, then you can escape the character using a backslash:
65
4.1. What Is a String?
Note
When you work on a project, it’s a good idea to use only single
quotes or only double quotes to delimit every string.
Keep in mind that there really isn’t a right or wrong choice! The
goal is to be consistent because consistency helps make your
code easier to read and understand.
Strings can contain any valid Unicode character. For example, the
string "We're #1!" contains the pound sign (#) and "1234" contains num-
bers. "×Pýŧħøŋ×" is also a valid Python string!
Python has a built-in len() function that you can use to determine the
length of a string. To see how it works, type the following into IDLE’s
interactive window:
>>> len("abc")
3
You can also use len() to get the length of a string that’s assigned to a
variable:
First, you assign the string "abc" to the variable letters. Then you use
len() to get the length of letters, which is 3.
66
4.1. What Is a String?
Multiline Strings
The PEP 8 style guide recommends that each line of Python code con-
tain no more than seventy-nine characters—including spaces.
Note
PEP 8’s seventy-nine-character line length is a recommenda-
tion, not a rule. Some Python programmers prefer a slightly
longer line length.
To deal with long strings, you can break them up across multiple lines
into multiline strings. For example, suppose you need to fit the
following text into a string literal:
There are a couple of ways to tackle this. One way is to break the string
up across multiple lines and put a backslash (\) at the end of all but the
67
4.1. What Is a String?
last line. To be PEP 8 compliant, the total length of the line, including
the backslashes, must be seventy-nine characters or fewer.
Here’s how you could write the paragraph as a multiline string using
the backslash method:
Notice that you don’t have to close each line with a quotation mark.
Normally, Python would get to the end of the first line and complain
that you didn’t close the string with a matching double quote. With a
backslash at the end, you can keep writing the same string on the next
line.
You can also create multiline strings using triple quotes (""" or ''') as
delimiters. Here’s how to write a long paragraph using this approach:
68
4.2. Concatenation, Indexing, and Slicing
Notice how the second and third lines in the output are indented in
exactly the same way as the string literal.
Review Exercises
You can nd the solutions to these exercises and many other bonus
resources online at realpython.com/python-basics/resources
1. Print a string that uses double quotation marks inside the string.
2. Print a string that uses an apostrophe inside the string.
3. Print a string that spans multiple lines with whitespace preserved.
4. Print a string that is coded on multiple lines but gets printed on a
single line.
69
4.2. Concatenation, Indexing, and Slicing
String Concatenation
You can combine, or concatenate, two strings using the + operator:
In this example, the string concatenation occurs on the third line. You
concatenate string1 and string2 using +, and then you assign the re-
sult to the variable magic_string. Notice that the two strings are joined
without any whitespace between them.
You can use string concatenation to join two related strings, such as
joining a first name and a last name into a full name:
Here, you use string concatenation twice on the same line. First, you
concatenate first_name with " " to ensure a space appears after the
first name in the final string. This produces the string "Arthur ", which
you then concatenate with last_name to produce the full name "Arthur
Dent".
70
4.2. Concatenation, Indexing, and Slicing
String Indexing
Each character in a string has a numbered position called an index.
You can access the character at the nth position by putting the number
n between two square brackets ([]) immediately after the string:
>>> flavor[0]
'f'
Important
The following figure shows the index for each character of the string
"fig pie":
| f | i | g | | p | i | e |
0 1 2 3 4 5 6
71
4.2. Concatenation, Indexing, and Slicing
If you try to access an index beyond the end of a string, then Python
raises an IndexError:
>>> flavor[9]
Traceback (most recent call last):
File "<pyshell#4>", line 1, in <module>
flavor[9]
IndexError: string index out of range
The largest index in a string is always one less than the string’s length.
Since "fig pie" has a length of seven, the largest index allowed is 6.
>>> flavor[-1]
'e'
The last character in a string has index -1, which for "fig pie" is the
letter e. The second to last character i has index -2, and so on.
The following figure shows the negative index for each character in
the string "fig pie":
| f | i | g | | p | i | e |
-7 -6 -5 -4 -3 -2 -1
Just like with positive indices, Python raises an IndexError if you try to
access a negative index less than the index of the first character in the
string:
>>> flavor[-10]
Traceback (most recent call last):
File "<pyshell#5>", line 1, in <module>
flavor[-10]
IndexError: string index out of range
Negative indices may not seem useful at first, but sometimes they’re
a better choice than a positive index.
72
4.2. Concatenation, Indexing, and Slicing
One way to get the last character of a string is to calculate the final
index using len():
final_index = len(user_input) - 1
last_character = user_input[final_index]
Getting the final character with the index -1 takes less typing and
doesn’t require an intermediate step to calculate the final index:
last_character = user_input[-1]
String Slicing
Suppose you need a string containing just the first three letters of the
string "fig pie". You could access each character by index and con-
catenate them like this:
If you need more than just the first few letters of a string, then get-
ting each character individually and concatenating them together is
clumsy and long-winded. Fortunately, Python provides a way to do
this with much less typing.
73
4.2. Concatenation, Indexing, and Slicing
Here’s what this looks like for the string "fig pie":
| f | i | g | | p | i | e |
0 1 2 3 4 5 6 7
So, for "fig pie", the slice [0:3] returns the string "fig", and the slice
[3:7] returns the string " pie".
If you omit the first index in a slice, then Python assumes you want to
start at index 0:
>>> flavor[:3]
'fig'
The slice [:3] is equivalent to the slice [0:3], so flavor[:3] returns the
first three characters in the string "fig pie".
Similarly, if you omit the second index in the slice, then Python as-
sumes you want to return the substring that begins with the character
74
4.2. Concatenation, Indexing, and Slicing
whose index is the first number in the slice and ends with the last char-
acter in the string:
>>> flavor[3:]
' pie'
For "fig pie", the slice [3:] is equivalent to the slice [3:7]. Since the
character at index 3 is a space, flavor[3:9] returns the substring that
starts with the space and ends with the last letter: " pie".
If you omit both the first and second numbers in a slice, you get a
string that starts with the character at index 0 and ends with the last
character. In other words, omitting both numbers in a slice returns
the entire string:
>>> flavor[:]
'fig pie'
It’s important to note that, unlike with string indexing, Python won’t
raise an IndexError when you try to slice between boundaries that fall
outside the beginning or ending boundaries of a string:
>>> flavor[:14]
'fig pie'
>>> flavor[13:15]
''
In this example, the first line gets the slice from the beginning of the
string up to but not including the fourteenth character. The string
assigned to flavor has a length of seven, so you might expect Python
to throw an error. Instead, it ignores any nonexistent indices and re-
turns the entire string "fig pie".
The third line shows what happens when you try to get a slice in which
the entire range is out of bounds. flavor[13:15] attempts to get the
thirteenth and fourteenth characters, which don’t exist. Instead of
raising an error, Python returns the empty string ("").
75
4.2. Concatenation, Indexing, and Slicing
Note
The empty string is called empty because it doesn’t contain any
characters. You can create it by writing two quotation marks
with nothing between them:
empty_string = ""
You can use negative numbers in slices. The rules for slices with nega-
tive numbers are exactly the same as the rules for slices with positive
numbers. It helps to visualize the string as slots with the boundaries
labeled with negative numbers:
| f | i | g | | p | i | e |
-7 -6 -5 -4 -3 -2 -1
Just like before, the slice [x:y] returns the substring starting at index
x and going up to but not including y. For instance, the slice [-7:-4]
returns the first three letters of the string "fig pie":
>>> flavor[-7:-4]
'fig'
Notice, however, that the rightmost boundary of the string does not
have a negative index. The logical choice for that boundary would
seem to be the number 0, but that doesn’t work.
76
4.2. Concatenation, Indexing, and Slicing
Instead of returning the entire string, [-7:0] returns the empty string:
>>> flavor[-7:0]
''
If you need to include the final character of a string in your slice, then
you can omit the second number:
>>> flavor[-7:]
'fig pie'
Of course, using flavor[-7:] to get the entire string is a bit odd consid-
ering that you can use the variable flavor without the slice to get the
same result!
Slices with negative indices are useful, though, for getting the last few
characters in a string. For example, flavor[-3:] is "pie".
77
4.2. Concatenation, Indexing, and Slicing
Python throws a TypeError and tells you that str objects don’t support
item assignment.
If you want to alter a string, then you must create an entirely new
string. To change the string "goal" to the string "foal", you can use a
string slice to concatenate the letter "f" with everything but the first
letter of the word "goal":
First, you assign the string "goal" to the variable word. Then you con-
catenate the slice word[1:], which is the string "oal", with the letter "f"
to get the string "foal". If you’re getting a different result here, then
make sure you’re including the colon character (:) as part of the string
slice.
Review Exercises
You can nd the solutions to these exercises and many other bonus
resources online at realpython.com/python-basics/resources
78
4.3. Manipulate Strings With Methods
Let’s go!
The dot (.) tells Python that what follows is the name of a method—
the lower() method in this case.
Note
We’ll refer to string methods with a dot (.) at the beginning of
their names. For example, .lower() is written with a leading dot
instead of as lower().
79
4.3. Manipulate Strings With Methods
String methods don’t just work on string literals. You can also use
.lower() on a string assigned to a variable:
>>> name.upper()
'JEAN-LUC PICARD'
Compare the .upper() and .lower() string methods to the len() func-
tion you saw in the last section. Aside from the different results of
these functions, the important distinction here is how they’re used.
>>> len(name)
15
80
4.3. Manipulate Strings With Methods
There are three string methods that you can use to remove whitespace
from a string:
1. .rstrip()
2. .lstrip()
3. .strip()
In this example, the string "Jean-Luc Picard " has five trailing spaces.
You use .rstrip() to remove trailing spaces from the right-hand side
of the string. This returns the new string "Jean-Luc Picard", which no
longer has the spaces at the end.
To remove whitespace from both the left and the right sides of the
string at the same time, use .strip():
81
4.3. Manipulate Strings With Methods
>>> starship.startswith("En")
True
You can use .endswith() to determine if a string ends with certain char-
acters:
>>> starship.endswith("rise")
True
82
4.3. Manipulate Strings With Methods
>>> starship.endswith("risE")
False
Note
The True and False values are not strings. They are a special kind
of data type called a Boolean value. You’ll learn more about
Boolean values in chapter 8.
If you aren’t careful, this can introduce subtle bugs into your program.
Try this out in IDLE’s interactive window:
assigned to name.
83
4.3. Manipulate Strings With Methods
Next, type starship followed by a period, but do not hit Enter . You
should see the following in the interactive window:
>>> starship.
Now wait for a couple of seconds. IDLE displays a list of every string
method, which you can scroll through using the arrow keys.
This even works with variable names. Try typing just the first few let-
ters of starship and pressing Tab . If you haven’t defined any other
names that share those first letters, then IDLE completes the name
starship for you.
Review Exercises
You can nd the solutions to these exercises and many other bonus
resources online at realpython.com/python-basics/resources
84
4.4. Interact With User Input
string1 = "Becomes"
string2 = "becomes"
string3 = "BEAR"
string4 = " bEautiful"
5. Using the same four strings from exercise 4, write a program that
uses string methods to alter each string so that .startswith("be")
returns True for all of them.
In this section, you’ll learn how to get some input from a user with
input(). You’ll write a program that asks a user to input some text and
then displays that text back to them in uppercase.
>>> input()
When you press Enter , it looks like nothing happens. The cursor
moves to a new line, but a new >>> doesn’t appear. Python is waiting
for you to enter something!
85
4.4. Interact With User Input
>>> input()
Hello there!
'Hello there!'
>>>
The text you entered is repeated on a new line with single quotes.
That’s because input() returns as a string any text entered by the user.
input() displays the prompt and waits for the user to type something.
When the user hits Enter , input() returns their input as a string that
can be assigned to a variable and used to do something in your pro-
gram.
To see how input() works, type the following code into IDLE’s editor
window:
The single space at the end of the string "Hey, what's up? " makes sure
that when the user starts to type, the text is separated from the prompt
with a space. When the user types a response and presses Enter , their
response is assigned to the user_input variable.
86
4.4. Interact With User Input
Once you have input from a user, you can do something with it. For
example, the following program takes user input, converts it to upper-
case with .upper(), and prints the result:
Try typing this program into IDLE’s editor window and running it.
What else can you think of to do with the input?
Review Exercises
You can nd the solutions to these exercises and many other bonus
resources online at realpython.com/python-basics/resources
1. Write a program that takes input from the user and displays that
input back.
2. Write a program that takes input from the user and displays the
input in lowercase.
3. Write a program that takes input from the user and displays the
number of characters in the input.
87
4.5. Challenge: Pick Apart Your User’s Input
For example, if the user input is "no", then the program should display
the following output:
For now, it’s okay if your program crashes when the user enters noth-
ing as input—that is, when they just hit Enter instead of typing some-
thing. You’ll learn a couple of ways to deal with this situation in an
upcoming chapter.
You can nd the solutions to this code challenge and many other bonus
resources online at realpython.com/python-basics/resources
In this section, you’ll learn how to deal with strings of numbers. You’ll
see how arithmetic operations work on strings and how they often lead
to surprising results. You’ll also learn how to convert between strings
and number types.
88
4.6. Working With Strings and Numbers
actual numbers. For instance, try this bit of code out in IDLE’s inter-
active window:
num * 3 concatenates three instances of the string "12" and returns the
string "121212".
You can move the number on the right-hand side of the expression num
* 3 to the left, and the result is unchanged:
>>> 3 * num
'121212'
What do you think happens if you use the operator between two
strings?
*
89
4.6. Working With Strings and Numbers
Python raises a TypeError and tells you that you can’t multiply a se-
quence by a non-integer.
Note
A sequence is any Python object that supports accessing ele-
ments by index. Strings are sequences. You’ll learn about other
sequence types in chapter 9.
When you use the * operator with a string, Python always expects an
integer on the other side of the operator.
What do you think happens when you try to add a string and a num-
ber?
>>> "3" + 3
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: can only concatenate str (not "int") to str
90
4.6. Working With Strings and Numbers
If you entered the number 2 at the prompt, then you would expect the
output to be 4. But in this case, you would get 22. Remember, input()
always returns a string, so if you input 2, then num is assigned the string
"2", not the integer 2. Therefore, the expression num * 2 returns the
string "2" concatenated with itself, which is "22".
int() stands for integer and converts objects into whole numbers,
whereas float() stands for oating-point number and converts ob-
jects into numbers with decimal points. Here’s what using each one
looks like in the interactive window:
>>> int("12")
12
>>> float("12")
12.0
91
4.6. Working With Strings and Numbers
>>> int("12.0")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: '12.0'
Even though the extra 0 after the decimal place doesn’t add any value
to the number, Python won’t change 12.0 into 12 because it would re-
sult in a loss of precision.
Let’s revisit the program from the beginning of this section and see
how to fix it. Here’s the code again:
You can fix the problem by passing num to either int() or float(). Since
the prompts asks the user to input a number, and not specifically an
integer, let’s convert num to a floating-point number:
Now when you run this program and input 2, you get 4.0 as expected.
Try it out!
92
4.6. Working With Strings and Numbers
>>> num_pancakes = 10
>>> "I am going to eat " + num_pancakes + " pancakes."
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: can only concatenate str (not "int") to str
>>> num_pancakes = 10
>>> "I am going to eat " + str(num_pancakes) + " pancakes."
'I am going to eat 10 pancakes.'
>>> total_pancakes = 10
>>> pancakes_eaten = 5
>>> "Only " + str(total_pancakes - pancakes_eaten) + " pancakes left."
'Only 5 pancakes left.'
In the next section, you’ll learn how to format strings neatly to display
values in a nice, readable manner. Before you move on, though, check
your understanding with the following review exercises.
93
4.7. Streamline Your Print Statements
Review Exercises
You can nd the solutions to these exercises and many other bonus
resources online at realpython.com/python-basics/resources
3. Create a string object and an integer object, then display them side
by side with a single print statement using str().
4. Write a program that uses input() twice to get two numbers from
the user, multiplies the numbers together, and displays the result.
If the user enters 2 and 4, then your program should print the
following text:
>>> name + " has " + str(heads) + " heads and " + str(arms) + " arms"
'Zaphod has 2 heads and 3 arms'
This code isn’t the prettiest, and keeping track of what goes inside or
outside the quotes can be tough. Fortunately, there’s another way of
interpolating strings: formatted string literals, more commonly
94
4.7. Streamline Your Print Statements
known as f-strings.
There are two important things to notice about the above example:
1. The string literal starts with the letter f before the opening quota-
tion mark.
2. Variable names surrounded by curly braces ({}) are replaced by
their corresponding values without using str().
You can also insert Python expressions between the curly braces. The
expressions are replaced with their result in the string:
>>> n = 3
>>> m = 4
>>> f"{n} times {m} is {n*m}"
'3 times 4 is 12'
f-strings are available only in Python version 3.6 and above. In ear-
lier versions of Python, you can use .format() to get the same results.
Returning to the Zaphod example, you can use .format() to format the
string like this:
95
4.8. Find a String in a String
Review Exercises
You can nd the solutions to these exercises and many other bonus
resources online at realpython.com/python-basics/resources
1. Create a float object named weight with the value 0.2, and create
a string object named animal with the value "newt". Then use these
objects to print the following string using only string concatena-
tion:
The value that .find() returns is the index of the first occurrence of the
string you pass to it. In this case, "surprise" starts at the fifth character
of the string "the surprise is in here somewhere", which has index 4
because counting starts at zero.
96
This is a sample from “Python Basics: A Practical
Introduction to Python 3”
With the full version of the book you get a complete Python curriculum
to go all the way from beginner to intermediate-level. Every step along
the way is explained and illustrated with short & clear code samples.
Coding exercises within each chapter and our interactive quizzes help
fast-track your progress and ensure you always know what to focus on
next.