PythonBasics: APracticalIntroduction
toPython3
RealPython
PythonBasics: APracticalIntroductiontoPython3
RevisedandUpdated4thEdition
DavidAmos,DanBader,JoannaJablonski,FletcherHeisler
Copyright©Real Python (
realpython.com),2012–2020
For onlineinformation and ordering of this and other books byReal
Python, please visit
realpython.com. For more information, please
contactusat[email protected].
ISBN:9781775093329(paperback)
ISBN:9781775093336(electronic)
CoverdesignbyAldrenSantos
AdditionaleditingandproofreadingbyJacobSchmitt
“Python” and the Python logos are trademarks or registered trade-
marks of thePythonSoftware Foundation, usedby Real Python with
permissionfromtheFoundation.
Thankyoufordownloadingthisebook. Thisebookislicensedforyour
personalenjoymentonly. Thisebookmaynotberesoldorgivenaway
tootherpeople. Ifyouwouldliketosharethisbookwithanotherper-
son, please purchase an additional copy for each recipient. If you’re
readingthisbookanddidnotpurchaseit,orifitwasnotpurchasedfor
your use only, then please return to
realpython.com/pybasics-book
andpurchaseyourowncopy. Thankyouforrespectingthehardwork
behindthisbook.
This is a sample from “Python Basics: A Practical
Introduction to Python 3”
WiththefullversionofthebookyougetacompletePythoncurriculum
togoallthewayfrombeginnertointermediate-level. Everystepalong
thewayisexplainedandillustratedwithshort&clearcodesamples.
Codingexerciseswithineachchapterandourinteractivequizzeshelp
fast-trackyourprogressandensureyoualwaysknowwhattofocuson
next.
Become a fluent Pythonista and gain programming knowledge you
canapplyinthereal-world,today:
If you enjoyed the sample chapters you can purchase a full
version of the book at
realpython.com/pybasics-book
What Pythonistas Say About Python Basics: A Practical In-
troduction to Python 3
“I love [the book]! The wording is casual, easy to understand, and
makes the information ow well. I never feel lost in the material, and
it’s not too dense so it’s easy for me to review older chapters over and
over.
I’ve looked at over 10 dierent Python tutorials/books/online courses,
and I’ve probably learned the most from Real Python!”
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
“I oundered for a long time trying to teach myself. I slogged through
dozens of incomplete online tutorials. I snoozed through hours of bor-
ing screencasts. I gave up on countless crufty books from big-time
publishers. And then I found Real Python.
The easy-to-follow, step-by-step instructions break the big concepts
down into bite-sized chunks written in plain English. The authors
never forget their audience and are consistently thorough and detailed
in their explanations. I’m up and running now, but I constantly refer
to the material for guidance.”
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.
Once again: MANY THANKS!”
Kamil
“What I found great about the Real Python courses compared to others
is how they explain things in the simplest way possible.
A lot of courses, in any discipline really, require the learning of a lot of
jargon when in fact what is being taught could be taught quickly and
succinctly without too much of it. The courses do a very good job of
keeping the examples interesting.”
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.
The ow of the lessons works perfectly throughout. The exercises truly
helped along the way and you feel very accomplished when you nish
up the book. I think you have a gift for making Python seem more
attainable to people outside the programming world.
This is something I never thought I would be doing or learning and
with a little push from you I am learning it and I can see that it will be
nothing but benecial to me in the future!”
Shea Klusewicz
“The authors of the courses have NOT forgotten what it is like to be
a beginner – something that many authors do – and assume noth-
ing about their readers, which makes the courses fantastic reads. The
courses are also accompanied by some great videos as well as plenty
of references for extra learning, homework assignments and example
code that you can experiment with and extend.
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’lllearnreal-worldprogrammingskillsfromacom-
munityofprofessionalPythonistasfromallaroundtheworld.
The
realpython.com website launched in 2012 and currently helps
more than three million Python developers each month with free
programmingtutorialsandin-depthlearningresources.
Everyonewhoworkedonthisbookisapractitioner withseveralyears
ofprofessionalexperienceinthesoftwareindustry. Herearethemem-
bersoftheReal Python tutorialteamwhoworkedonPython Basics:
David Amos isthecontenttechnicalleadforReal Python. Afterleav-
ingacademiain2015,Davidworkedinvarious 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
rewritingandupdatingthePython Basics curriculumtoPython3.
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-
sellingprogrammingbookforintermediatePythondevelopers.
Joanna Jablonski is the executive editor of Real Python. She likes
natural languages just as much as she likes programming languages.
Herloveforpuzzles,patterns,andpeskylittledetailsledhertofollow
acareer in translation. It was only a matter of time before she would
fall in love with a new language: Python! She joined Real Python in
2018andhasbeenhelpingPythonistaslevelupeversince.
Fletcher Heisler is the founder of Hunter2, where he teaches de-
velopers how to hack and secure modern web apps. As one of the
foundingmembersofReal Python,Fletcherwrote the first version of
thePythoncurriculumthisbookisbasedonin2012.
Contents
Contents 8
Foreword 13
1 Introduction 20
1.1 WhyThisBook? . . . . . . . . . . . . . . . . . . . . 21
1.2 AboutRealPython . . . . . . . . . . . . . . . . . . 23
1.3 HowtoUseThisBook . . . . . . . . . . . . . . . . . 24
1.4 BonusMaterialandLearningResources . . . . . . . 25
2 Setting Up Python 29
2.1 ANoteonPythonVersions . . . . . . . . . . . . . . 30
2.2 Windows . . . . . . . . . . . . . . . . . . . . . . . 31
2.3 macOS . . . . . . . . . . . . . . . . . . . . . . . . . 34
2.4 UbuntuLinux . . . . . . . . . . . . . . . . . . . . . 37
3 Your First Python Program 42
3.1 WriteaPythonProgram . . . . . . . . . . . . . . . 43
3.2 MessThingsUp . . . . . . . . . . . . . . . . . . . . 47
3.3 CreateaVariable . . . . . . . . . . . . . . . . . . . 50
3.4 InspectValuesintheInteractiveWindow . . . . . . 55
3.5 LeaveYourself Helpful Notes . . . . . . . . . . . . . 58
3.6 SummaryandAdditionalResources . . . . . . . . . 60
4 Strings and String Methods 62
4.1 WhatIsaString? . . . . . . . . . . . . . . . . . . . 63
4.2 Concatenation,Indexing,andSlicing . . . . . . . . . 69
8
Contents
4.3 ManipulateStringsWithMethods . . . . . . . . . . 79
4.4 InteractWith User Input . . . . . . . . . . . . . . . 85
4.5 Challenge: Pick Apart Your User’s Input . . . . . . . 88
4.6 WorkingWith Strings and Numbers . . . . . . . . . 88
4.7 StreamlineYourPrintStatements . . . . . . . . . . 94
4.8 FindaStringinaString . . . . . . . . . . . . . . . . 96
4.9 Challenge: Turn Your User Into a L33t H4x0r . . . . 99
4.10 Summary and Additional Resources . . . . . . . . . 100
5 Numbers and Math 102
5.1 IntegersandFloating-PointNumbers . . . . . . . . 103
5.2 ArithmeticOperators and Expressions . . . . . . . . 107
5.3 Challenge: Perform Calculations on User Input . . . 115
5.4 Make Python Lie to You . . . . . . . . . . . . . . . . 116
5.5 MathFunctionsandNumberMethods . . . . . . . . 118
5.6 Print Numbers in Style . . . . . . . . . . . . . . . . 123
5.7 ComplexNumbers . . . . . . . . . . . . . . . . . . 126
5.8 SummaryandAdditionalResources . . . . . . . . . 130
6 Functions and Loops 132
6.1 WhatIsaFunction,Really? . . . . . . . . . . . . . . 133
6.2 WriteYourOwnFunctions . . . . . . . . . . . . . . 137
6.3 Challenge: ConvertTemperatures . . . . . . . . . . 146
6.4 Runin Circles . . . . . . . . . . . . . . . . . . . . . 147
6.5 Challenge: Track Your Investments . . . . . . . . . . 156
6.6 UnderstandScope in Python . . . . . . . . . . . . . 157
6.7 SummaryandAdditionalResources . . . . . . . . . 162
7 Finding and Fixing Code Bugs 164
7.1 Use the Debug Control Window . . . . . . . . . . . 165
7.2 SquashSomeBugs . . . . . . . . . . . . . . . . . . 171
7.3 Summary and Additional Resources . . . . . . . . . 179
8 Conditional Logic and Control Flow 181
8.1 CompareValues . . . . . . . . . . . . . . . . . . . . 182
8.2 AddSomeLogic . . . . . . . . . . . . . . . . . . . . 186
8.3 Control the Flow of Your Program . . . . . . . . . . 194
9
Contents
8.4 Challenge: FindtheFactorsofaNumber . . . . . . . 206
8.5 BreakOutofthePattern . . . . . . . . . . . . . . . 207
8.6 RecoverFromErrors . . . . . . . . . . . . . . . . . 211
8.7 Simulate Events and Calculate Probabilities . . . . . 217
8.8 Challenge: SimulateaCoinTossExperiment . . . . . 223
8.9 Challenge: SimulateanElection . . . . . . . . . . . 223
8.10 Summary and Additional Resources . . . . . . . . . 224
9 Tuples, Lists, and Dictionaries 226
9.1 TuplesAreImmutableSequences . . . . . . . . . . . 227
9.2 ListsAreMutableSequences . . . . . . . . . . . . . 237
9.3 Nesting,Copying,andSortingTuplesandLists . . . 251
9.4 Challenge: List of lists . . . . . . . . . . . . . . . . . 257
9.5 Challenge: Wax Poetic . . . . . . . . . . . . . . . . 258
9.6 StoreRelationships in Dictionaries . . . . . . . . . . 260
9.7 Challenge: CapitalCityLoop . . . . . . . . . . . . . 270
9.8 HowtoPickaDataStructure . . . . . . . . . . . . . 272
9.9 Challenge: Cats With Hats . . . . . . . . . . . . . . 273
9.10 SummaryandAdditionalResources . . . . . . . . . 274
10 Object-Oriented Programming (OOP) 276
10.1 Define a Class . . . . . . . . . . . . . . . . . . . . . 277
10.2 Instantiate an Object . . . . . . . . . . . . . . . . . 281
10.3 Inherit From Other Classes . . . . . . . . . . . . . . 287
10.4 Challenge: ModelaFarm . . . . . . . . . . . . . . . 296
10.5 SummaryandAdditionalResources . . . . . . . . . 297
11 Modules and Packages 298
11.1 WorkingWithModules . . . . . . . . . . . . . . . . 299
11.2 WorkingWithPackages . . . . . . . . . . . . . . . . 310
11.3 Summary and Additional Resources . . . . . . . . . 318
12 File Input and Output 320
12.1 FilesandtheFileSystem . . . . . . . . . . . . . . . 321
12.2 WorkingWithFilePathsinPython . . . . . . . . . . 324
12.3 CommonFileSystemOperations . . . . . . . . . . . 333
12.4 Challenge: Move All Image Files to a New Directory . 350
10
Contents
12.5 ReadingandWritingFiles . . . . . . . . . . . . . . 351
12.6 ReadandWriteCSVData . . . . . . . . . . . . . . . 366
12.7 Challenge: CreateaHighScoresList . . . . . . . . . 377
12.8 SummaryandAdditionalResources . . . . . . . . . 378
13 Installing Packages With pip 379
13.1 Installing Third-Party Packages With pip . . . . . . . 380
13.2 ThePitfallsofThird-PartyPackages . . . . . . . . . 390
13.3 SummaryandAdditionalResources . . . . . . . . . 392
14 Creating and Modifying PDF Files 394
14.1 ExtractingTextFromaPDF . . . . . . . . . . . . . 395
14.2 ExtractingPagesFromaPDF . . . . . . . . . . . . . 402
14.3 Challenge: PdfFileSplitter Class . . . . . . . . . . . 409
14.4 Concatenating and Merging PDFs . . . . . . . . . . 410
14.5 Rotating and Cropping PDF Pages . . . . . . . . . . 417
14.6 Encrypting and Decrypting PDFs . . . . . . . . . . . 428
14.7 Challenge: UnscrambleaPDF . . . . . . . . . . . . 433
14.8 CreatingaPDFFileFromScratch . . . . . . . . . . 433
14.9 Summary and Additional Resources . . . . . . . . . 440
15 Working With Databases 442
15.1 An Introduction to SQLite . . . . . . . . . . . . . . 443
15.2 LibrariesforWorkingWithOtherSQLDatabases . . 455
15.3 Summaryand Additional Resources . . . . . . . . . 456
16 Interacting With the Web 458
16.1 Scrape and Parse TextFromWebsites . . . . . . . . 459
16.2 Usean HTMLParsertoScrapeWebsites . . . . . . . 469
16.3 InteractWithHTMLForms . . . . . . . . . . . . . . 475
16.4 Interact With Websites in Real Time . . . . . . . . . 481
16.5 Summary and Additional Resources . . . . . . . . . 485
17 Scientic Computing and Graphing 487
17.1 UseNumPyforMatrixManipulation . . . . . . . . . 488
17.2 UseMatplotlibforPlottingGraphs . . . . . . . . . . 499
17.3 Summary and Additional Resources . . . . . . . . . 522
11
Contents
18 Graphical User Interfaces 523
18.1 AddGUIElementsWithEasyGUI . . . . . . . . . . 524
18.2 ExampleApp: PDFPageRotator . . . . . . . . . . . 536
18.3 Challenge: PDFPageExtractionApplication . . . . . 543
18.4 IntroductiontoTkinter . . . . . . . . . . . . . . . . 544
18.5 WorkingWithWidgets . . . . . . . . . . . . . . . . 548
18.6 ControllingLayoutWithGeometryManagers . . . . 573
18.7 Making Your Applications Interactive . . . . . . . . 592
18.8 ExampleApp: TemperatureConverter . . . . . . . . 602
18.9 ExampleApp: Text Editor . . . . . . . . . . . . . . 607
18.10Challenge: Return of the Poet . . . . . . . . . . . . . 616
18.11 SummaryandAdditionalResources . . . . . . . . . 618
19 Final Thoughts and Next Steps 620
19.1 Free Weekly Tips for Python Developers . . . . . . . 622
19.2 PythonTricks: The Book . . . . . . . . . . . . . . . 622
19.3 RealPythonVideoCourseLibrary . . . . . . . . . . 623
19.4 Acknowledgements . . . . . . . . . . . . . . . . . . 624
12
Foreword
Hello, and welcome to Python Basics: A Practical Introduction to
Python 3. Ihope you’re ready to learn why so many professional and
hobbyist developers are drawn to Python and how you can begin
usingitonyourownprojects,smallandlarge,rightaway.
This book is targeted at beginners who either know a little program-
mingbutnotthePythonlanguageandecosystemorarestartingfresh
withnoprogrammingexperiencewhatsoever.
Ifyoudon’thaveacomputersciencedegree,don’tworry. David,Dan,
Joanna, and Fletcher will guide you through the important comput-
ingconceptswhileteaching you thePythonbasicsand,justas impor-
tantly,skippingtheunnecessarydetailsatfirst.
Python Is a Full-Spectrum Language
When learning a new programming language, you don’t yet have the
experiencetojudgehowwellitwillserveyouinthelongrun. Ifyou’re
considering learning Python, let me assure you that this is a good
choice. OnekeyreasonisthatPythonisafull-spectrum language.
WhatdoImeanbythis? Somelanguagesareverygoodforbeginners.
They hold your hand and make programming super easy. We can go
totheextremeandlookatvisuallanguagessuchasScratch.
In Scratch, you get blocks that represent programming concepts like
variables,loops,methodcalls,andsoon,andyoudraganddropthem
on a visual surface. Scratch may be easy to get started with for sim-
13
Contents
ple programs, but you cannot build professional applications with it.
Name one Fortune 500 company that powers its core business logic
withScratch.
Comeupempty? Metoo,becausethatwouldbeinsanity.
Other languages are incredibly powerful for expert developers. The
most popular one in this category is likely C++ and its close relative,
C. Whichever web browser you used today was likely written in C or
C++. Youroperatingsystemrunningthatbrowserwasverylikelyalso
builtwithC/C++. Yourfavoritefirst-personshooterorstrategyvideo
game? Younailedit: C/C++.
You can do amazing things with these languages, but they are wholly
unwelcomingtonewcomerslookingforagentleintroduction.
You might not have read a lot of C++ code. It can almost make your
eyesburn. Here’sanexample,arealalbeitcomplexone:
template <typename T>
_Defer<void(*(PID<T>, void (T::*)(void)))
(const PID<T>&, void (T::*)(void))>
defer(const PID<T>& pid, void (T::*method)(void))
{
void (*dispatch)(const PID<T>&, void (T::*)(void)) =
&process::template dispatch<T>;
return std::tr1::bind(dispatch, pid, method);
}
Please,justno.
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
switchtoa“real”languagetobuildrealapplications. 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
supporttheserichapplications.
14
Contents
Python, on the other hand, is special. It is a full-spectrum language.
Weoften judge the simplicity ofa language based on the Hello, World
test. Thatis,whatsyntaxandactionsarenecessarytogetthelanguage
tooutputHello, World totheuser? InPython,itcouldn’tbesimpler:
print("Hello, World")
That’sit! However,Ifindthisanunsatisfyingtest.
TheHello, World testisusefulbutreallynotenoughtoshowthepower
or complexity of a language. Let’s try another example. Not every-
thinghereneedstomaketotalsense—justfollowalongtogettheZen
ofit. Thebookcoverstheseconceptsandmoreasyougothrough. The
next example is certainly something you could write as you get near
theendofthebook.
Here’s the new test: What would it take to write a program that ac-
cessesanexternalwebsite,downloadsthecontenttoyourappinmem-
ory, then displays a subsection of that content to the user? Let’s try
thatexperiment using Python 3 withthe help of the requests package
(whichneedstobeinstalled—moreonthatinchapter12):
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:
<h2>Please log in to access Mount Olympus:</h2>
This is the easy, getting-started side of the Python spectrum. A few
triviallinescanunleashincrediblepower. BecausePythonhasaccess
tosomanypowerfulbutwell-packagedlibraries,suchasrequests,it’s
oftendescribedashaving batteries included.
15
Contents
Sothereyouhaveasimpleyetpowerful starter example. On the real-
world side of things, many incredible applications have been written
inPythonaswell.
YouTube,theworld’smostpopularvideo streamingsite,iswritten in
Pythonandprocessesmorethanamillionrequestspersecond. Insta-
gramisanotherexampleof aPythonapplication. Closertohome, we
evenhaverealpython.comandmysites,suchastalkpython.fm.
This full-spectrum aspect of Python means that you can start with
the basics and adopt more advanced features as your application de-
mandsgrow.
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
buildtheappyouwanttobuildwithit.
But, for better or worse, the popularity of a programming language
is a strong indicator of the quality of libraries you’ll have available as
wellthenumberofjobopeningsyou’llfind. Inshort,youshouldtend
to gravitate toward more popular technologies as there will be more
choicesandintegrationsavailable.
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-
larquestion-and-answersiteforprogrammers.
StackOverflowrunsasitecalledStackOverflowTrendswhereyoucan
lookatthetrendsforvarioustechnologiesbytag. Whenyoucompare
16
Contents
Pythontotheotherlikelycandidatesyoucouldpicktolearnprogram-
ming,you’llseeoneisunliketheothers:
Youcanexplorethischartandcreatesimilarchartstothisoneoverat
insights.stackoverflow.com/trends.
Notice the incredible growth of Python compared to the flat or even
downwardtrendofthe other usual candidates! Ifyou’rebettingyour
future on the success of a given technology, which one would you
choosefromthislist?
That’s just one chart—what does it really tell us? Well, let’s look at
another. Stack Overflow does a yearlysurvey 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 shareof“developers who are
not developing with the language or technology but have expressed
interestindevelopingwithit.”
17
Contents
Again,inthegraphbelow,you’llseethatPythonistoppingthecharts
andiswellaboveevensecondplace:
If you agree with me that the relative popularity of a programming
languagematters,thenPythonisclearlyagoodchoice.
We Don’t Need You to Be a Computer Scientist
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
softwaredevelopers!”
That may or may not be true. But, more importantly, programming
(evenalittleprogramming)canbeapersonalsuperpowerforyou.
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-
queststogetdatafromtheWeb,canbeincrediblypowerfulforyouas
abiologist.
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
beyondyourcolleagues’tomakeityoursuperpower.
Dan and Real Python
Finally,letmeleaveyouwithacommentonyourauthors. DanBader
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.
TheyhaveauniqueviewintothePythonecosystemandarekeyedinto
whatbeginnersneedtoknow.
I’m confident leaving you in their hands on this Python journey. Go
forth and learn this amazing language using this great book. Most
importantly,remembertohavefun!
Michael Kennedy, Founder of Talk Python (
@mkennedy)
19
Chapter 1
Introduction
Welcome to Real Python’s Python Basics book, fully updated for
Python 3.9! In this book, you’ll learn real-world Python program-
mingtechniques,illustratedwithusefulandinterestingexamples.
Whether you’re a new programmer or a professional software devel-
oper looking to dive into a new language, this book will teach you all
the practical Python that you need to get started on projects of your
own.
No matter what your ultimate goals may be, if you work with a com-
puterat all, then you’ll soon be finding endless ways to improve your
life by automating tasks and solving problems through Python pro-
gramsthatyoucreate.
But what’s so great about Python as a programming language? For
one, Python is open source freeware, meaning you can download it
forfreeanduseitforanypurpose,commercialornot.
Python also has an amazing community that has built a number of
useful tools that you can use in your own programs. Need to work
withPDFdocuments? There’sacomprehensivetoolforthat. Wantto
collectdatafromwebpages? Noneedtostartfromscratch!
20
1.1. Why This Book?
Python was built to be easier to use than other programming lan-
guages. It’susuallymucheasiertoreadPythoncodeand muchfaster
towritecodeinPythonthaninotherlanguages.
Forinstance,here’ssomebasiccodewritteninC,anothercommonly
usedprogramminglanguage:
#include <stdio.h>
int main(void)
{
printf("Hello, World\n");
}
Alltheprogramdoesisshowthetext Hello, World onthescreen. That
wasalotofworktooutputonephrase! Here’sthesameprogramwrit-
teninPython:
print("Hello, World")
That’s pretty simple, right? The Python code is faster to write and
easiertoread. Wefindthatitlooksfriendlierandmoreapproachable,
too!
At the same time, Python has all the functionality of other languages
andmore. Youmightbesurprisedbyhowmanyprofessionalproducts
are built on Python code: Instagram, YouTube, Reddit, Spotify, to
namejustafew.
Pythonisnotonlyafriendlyandfunlanguagetolearn,butitalsopow-
ersthetechnologybehindmultipleworld-classcompaniesandoffers
fantasticcareeropportunitiesforanyprogrammerwhomastersit.
1.1 Why This Book?
Let’s face it: there’s an overwhelming amount of information about
Python on the Internet. But many beginners studying on their own
havetroublefiguringoutwhat tolearnand in what order tolearnit.
21
1.1. Why This Book?
Youmaybeasking yourself, What should I learn about Python inthe
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
inPythonorotherlanguages.
Python Basics is written in plain English and breaks down the core
concepts that you really need to know into bite-sized chunks. This
meansyou’lllearnenoughtobedangerouswithPython,fast.
Insteadofjustgoingthrougha boring list of languagefeatures,you’ll
see exactly how the different building blocks fit together and what’s
involvedinbuildingrealapplicationsandscriptswithPython.
Stepbystep,you’llmasterfundamentalPythonconceptsthatwillhelp
yougetstartedonyourjourneytowardlearningPython.
Many programming books try to cover every last possible variation
of every command, which makes it easy for readers to get lost in the
details. Thisapproachisgreatifyou’relookingforareferencemanual,
butit’sahorrible way to learn a programming language. Not only do
you spend most of your time cramming things into your head that
you’llneveruse,butyoualsodon’thaveanyfun!
Thisbookisbuiltonthe80/20principle,whichsuggeststhatyoucan
learnmostofwhatyouneedtoknowbyfocusingonafewcrucialcon-
cepts. We’llcover thecommandsandtechniquesusedinthevastma-
jority of cases and focus on how to program real-world solutions to
everydayproblems.
Thisway,weguaranteethatyouwill:
Learnusefulprogrammingtechniquesquickly
Spendlesstimestrugglingwithunimportantcomplications
FindmorepracticalusesforPythoninyourownlife
Havemorefunintheprocess
22
1.2. About Real Python
Onceyou’ve mastered the material in this book, you will have gained
astrongenoughfoundationthatventuringoutonyourownintomore
advancedterritorywillbeabreeze.
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-
cludingAmazon,RedHat,andMicrosoft.
ForPython Basics, we’ve thoroughly expanded, refined, and updated
thematerialsoyoucanbuildyourPythonskillsquicklyandefficiently.
1.2 About Real Python
At Real Python, you’ll learn real-world programming skills from a
communityofprofessionalPythonistasfromallaroundtheworld.
The
realpython.com website launched in 2012 and currently helps
more than three million Python developers each month with books,
programmingtutorials,andotherin-depthlearningresources.
Everyonewhoworked onthisbookisa Python practitioner recruited
from the Real Python team with several years of professional experi-
enceinthesoftwareindustry.
Here’swhereyoucanfindReal Python ontheWeb:
realpython.com
@realpythononTwitter
TheReal Python Newsletter
TheReal Python Podcast
23
1.3. How to Use This Book
1.3 How to Use This Book
The first half of this book is a quick but thorough overview of all the
Python fundamentals. You don’t need any prior experience with pro-
grammingtogetstarted. Thesecondhalfisfocusedonfindingpracti-
calsolutionstointeresting,real-worldcodingproblems.
Ifyou’reabeginner,thenwerecommendthatyougothroughthefirst
halfofthisbookfrombeginningtoend. Thesecondhalfcoverstopics
that don’t overlap as much, so you can jump around more easily, but
thechaptersdoincreaseindifficultyasyougoalong.
Ifyou’reamoreexperiencedprogrammer,thenyoumayfindyourself
headingtoward the second part of the book right away. But don’t ne-
glectgetting a strong foundation in the basicsfirst, and besure to fill
inanyknowledgegapsalongtheway.
Mostsections within a chapter are followed by review exercises to
helpyoumakesurethatyou’vemasteredallthetopicscovered. There
arealsoanumberof code challenges,whicharemoreinvolvedand
usuallyrequireyoutotietogetherseveraldifferentconceptsfrompre-
viouschapters.
Thepracticefilesthataccompanythisbookalsoincludefullsolutions
to the challenges as well as some of the trickier exercises. But to get
themostoutofthematerial,youshouldtryyourbesttosolvethechal-
lengeproblemsonyourownbeforelookingattheexamplesolutions.
Ifyou’recompletelynewto programming, then you maywanttosup-
plement the first few chapters with additional practice. We recom-
mend working through the entry-level tutorials available for free at
realpython.comtomakesureyou’reonsolidfooting.
If you have any questions or feedback about the book, you’re always
welcometo
contactusdirectly.
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
recommendthatyouavoidcopyingandpastingthecodeexamples.
You’ll learn the concepts better and pick up the syntax faster if you
typeouteachline ofcodeyourself. Plus,ifyou screwup—whichisto-
tallynormalandhappenstoalldevelopersonadailybasis—thesimple
actofcorrectingtyposwillhelpyoulearnhowtodebugyourcode.
Trytocompletethereviewexercisesandcodechallengesonyourown
before getting help from outside resources. With enough practice,
you’llmasterthismaterial—andhavefunalongtheway!
How Long Will It Take to Finish This Book?
If you’re already familiar with a programming language, then you
couldfinishthisbookinaslittleasthirty-fivetofortyhours. Ifyou’re
newtoprogramming,thenyoumayneedtospenduptoonehundred
hoursormore.
Takeyourtimeanddon’tfeellikeyouhavetorush. Programmingisa
super-rewardingbutcomplexskilltolearn. GoodluckonyourPython
journey. We’rerootingforyou!
1.4 Bonus Material and Learning
Resources
This book comes with a number of free bonus resources and down-
loads that you can access online at the link below. We’re also main-
taininganerratalistwithcorrectionsthere:
realpython.com/python-basics/resources
25
1.4. Bonus Material and Learning Resources
Interactive Quizzes
Mostchaptersinthisbookcomewithafreeonlinequiztocheckyour
learningprogress. Youcanaccessthequizzesusingthelinksprovided
at the end of the chapter. The quizzes are hosted on the Real Python
websiteandcanbeviewedonyourphoneorcomputer.
Eachquiztakesyouthroughaseriesofquestionsrelated toaparticu-
lar chapter in the book. Some of them are multiple choice, some will
ask you to type in an answer, and some will require you to write ac-
tual Python code. As you make your way through each quiz, it will
keepscoreofwhichquestionsyouansweredcorrectly.
At the end of the quiz, you’ll receive a grade based on your result. If
youdon’tscore100percentonyourfirsttry,don’tfret! Thesequizzes
aremeanttochallengeyou. It’s expected that you’ll go through them
severaltimes,improvingyourscorewitheachrun.
Exercises Code Repository
This book has an accompanying
code repository on the Web contain-
ingexample source code as wellas the answers to exercisesand code
challenges. The repository is broken up by chapter, so you can check
your code against the solutions provided by us after you finish each
chapter. Here’sthelink:
realpython.com/python-basics/exercises
Note
ThecodefoundinthisbookhasbeentestedwithPython3.9on
Windows,macOS,andLinux.
26
1.4. Bonus Material and Learning Resources
Example Code License
TheexamplePythonscriptsassociatedwiththisbookarelicensedun-
der a
Creative Commons Public Domain (CC0) License. This means
thatyou’rewelcometouseanyportionofthecodeforany purposein
yourownprograms.
Formatting Conventions
Codeblockswillbeusedtopresentexamplecode:
# This is Python code:
print("Hello, World")
TerminalcommandsfollowtheUnixformat:
$ # This is a terminal command:
$ python hello-world.py
(Thedollarsignsarenotpartofthecommand.)
Monospace text willbeusedtodenoteafilename: hello-world.py.
Bold text will be used to denote a new or important term.
Keyboardshortcutswillbeformattedasfollows:
Ctrl
+
S
Menushortcutswillbeformattedasfollows:
File New File
Notesandimportantinformationwillbehighlightedasfollows:
Note
This is a note filled in with placeholder text. The quick brown
fox jumps over the lazy dog. The quick brown Python slithers
overthelazyhog.
27
1.4. Bonus Material and Learning Resources
Feedback and Errata
We welcome ideas, suggestions, feedback, and the occasional rant.
Did you find a topic confusing? Did you find an error in the text or
code? Didweleaveoutatopicthatyou’dlovetoknowmoreabout?
We’re always looking to improve our teaching materials. Whatever
thereason,pleasesendinyourfeedbackatthelinkbelow:
realpython.com/python-basics/feedback
28
Chapter 2
Setting Up Python
This book is about programming computers with Python. You could
readthis book from cover to cover without ever touching a keyboard,
butyou’dmissoutonthefunpart—coding!
To get the most out of this book, you need a computer with Python
installedonitandawaytocreate,edit,andsavePythoncodefiles.
In this chapter, you’ll learn how to:
InstallthelatestversionofPython3onyourcomputer
Open IDLE, Python’s built-in Integrated Development and
LearningEnvironment
Let’sgetstarted!
29
2.1. A Note on Python Versions
2.1 A Note on Python Versions
Many operating systems, including macOS and Linux, come with
Python preinstalled. The version of Python that comes with your
operatingsystemiscalledthesystem Python.
ThesystemPythonisusedbyyouroperatingsystemandisusuallyout
ofdate. It’s essentialthatyouhavethemostrecentversionof Python
so that you can successfully follow along with the examples in this
book.
Important
DonotattempttouninstallthesystemPython!
YoucanhavemultipleversionsofPythoninstalledonyourcomputer.
In this chapter, you’ll install the latest version of Python 3 alongside
anysystemPythonthatmayalreadyexistonyourmachine.
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-
mentissetupforfollowingalongwiththisbook.
This chapter is split into three sections: Windows, macOS, and
UbuntuLinux. Findthesectionforyour operating system andfollow
thestepstogetsetup,thenskipaheadtothenextchapter.
Ifyouhaveadifferentoperatingsystem,thencheckoutReal Python’s
“Python 3 Installation & Setup Guide” to see if your OS is covered.
Readersontabletsandmobiledevicescanrefertothe“OnlinePython
Interpreters”
sectionforsomebrowser-basedoptions.
30
2.2. Windows
2.2 Windows
FollowthesestepstoinstallPython3andopenIDLEonWindows.
Important
Thecode in this book is tested only against Python installedas
describedinthissection.
Beaware that if you have installed Python through some other
means,suchasAnacondaPython,youmayencounterproblems
whenrunningsomeofthecodeexamples.
Install Python
Windows doesn’t typically come with a system Python. Fortunately,
installation involves little more than downloading and running the
Pythoninstallerfromthe
Python.orgwebsite.
Step 1: Download the Python 3 Installer
OpenawebbrowserandnavigatetothefollowingURL:
https://www.python.org/downloads/windows/
Click Latest Python 3 Release - Python 3.x.x located beneath the
“Python Releases for Windows” heading near the top of the page. As
ofthiswriting,thelatestversionwasPython3.9.
Then scroll to the bottom and click Windows x86-64 executable in-
staller tostartthedownload.
Note
If your system has a 32-bit processor, then you should choose
the32-bitinstaller. Ifyouaren’tsureifyourcomputeris32-bit
or64-bit,stickwiththe64-bitinstallermentionedabove.
31
2.2. Windows
Step 2: Run the Installer
Open your Downloads folder in Windows Explorer and double-click
the file to run the installer. A dialog that looks like the following one
willappear:
It’sokayifthePythonversionyou see is greater than 3.9.0 as long as
theversionisnotlessthan3.
Important
MakesureyouselecttheboxthatsaysAdd Python 3.x to PATH.
If you install Python without selecting this box, then you can
runtheinstalleragainandselectit.
Click
Install Now
toinstallPython3. Waitfortheinstallationtofinish,
thencontinuetoopenIDLE.
32
2.2. Windows
Open IDLE
YoucanopenIDLEintwosteps:
1. ClicktheStartmenuandlocatethePython3.9folder.
2. OpenthefolderandselectIDLE (Python 3.9).
IDLEopensaPython shell inanewwindow. ThePythonshellisan
interactive environment that allows you to type in Python code and
executeitimmediately. It’sagreatwaytogetstartedwithPython!
Note
While you’re free to use a code editor other than IDLE if you
prefer, note that some chapters, especially chapter 7, “Finding
andFixingCodeBugs,”docontainmaterialspecifictoIDLE.
ThePythonshellwindowlookslikethis:
At the top of the window, you can see the version of Python that is
runningandsomeinformationabouttheoperatingsystem. Ifyousee
a version less than 3.9, then you may need to revisit the installation
instructionsintheprevioussection.
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-
ingprogress. Youcanaccessthequizusingyourphoneorcom-
puteratthefollowingwebaddress:
realpython.com/quizzes/pybasics-setup
NowthatyouhavePythoninstalled,let’sgetstraightintowritingyour
firstPythonprogram! Goaheadandmoveontochapter3.
2.3 macOS
FollowthesestepstoinstallPython3andopenIDLEonmacOS.
Important
Thecode in this book is tested only against Python installedas
describedinthissection.
Beaware that if you have installed Python through some other
means,suchasAnacondaPython,youmayencounterproblems
whenrunningsomeofthecodeexamples.
Install Python
ToinstallthelatestversionofPython3onmacOS,downloadandrun
theofficialinstallerfromthe
Python.orgwebsite.
Step 1: Download the Python 3 Installer
OpenawebbrowserandnavigatetothefollowingURL:
https://www.python.org/downloads/mac-osx/
34
2.3. macOS
Click Latest Python 3 Release - Python 3.x.x located beneath the
“PythonReleases for Mac OSX” heading near thetop of the page. As
ofthiswriting,thelatestversionwasPython3.9.
Thenscrolltothebottomofthepageandclick macOS 64-bit installer
tostartthedownload.
Step 2: Run the Installer
OpenFinderanddouble-clickthedownloadedfiletoruntheinstaller.
Adialogboxthatlookslikethefollowingwillappear:
Press
Continue
afewtimesuntilyouareaskedtoagreetothesoftware
licenseagreement. Thenclick
Agree
.
You’llbeshownawindowthattellsyouwherePythonwillbeinstalled
andhowmuchspaceitwilltake. Youmostlikelydon’twanttochange
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
installerwindow.
Open IDLE
YoucanopenIDLEinthreesteps:
1. OpenFinderandclickApplications.
2. Double-clickthePython3.9folder.
3. Double-clicktheIDLEicon.
IDLEopensaPython shell inanewwindow. ThePythonshellisan
interactive environment that allows you to type in Python code and
executeitimmediately. It’sagreatwaytogetstartedwithPython!
Note
While you’re free to use a code editor other than IDLE if you
prefer, note that some chapters, especially chapter 7, “Finding
andFixingCodeBugs,”docontainmaterialspecifictoIDLE.
ThePythonshellwindowlookslikethis:
36
2.4. Ubuntu Linux
At the top of the window, you can see the version of Python that is
runningandsomeinformationabouttheoperatingsystem. Ifyousee
a version less than 3.9, then you may need to revisit the installation
instructionsintheprevioussection.
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-
ingprogress. Youcanaccessthequizusingyourphoneorcom-
puteratthefollowingwebaddress:
realpython.com/quizzes/pybasics-setup
NowthatyouhavePythoninstalled,let’sgetstraightintowritingyour
firstPythonprogram! Goaheadandmoveontochapter3.
2.4 Ubuntu Linux
Follow these steps to install Python 3 and open IDLE on Ubuntu
Linux.
Important
Thecode in this book is tested only against Python installedas
describedinthissection.
Beaware that if you have installed Python through some other
means,suchasAnacondaPython,youmayencounterproblems
whenrunningsomeofthecodeexamples.
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
maybePython2insteadofPython3.
Tofindoutwhatversion(s)youhave,openaterminalwindowandtry
thefollowingcommands:
$ python --version
$ python3 --version
One or more of these commands should respond with a version, as
below:
$ 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
onwhich version of Ubuntu you’re running. Youcan determine your
localUbuntuversionbyrunningthefollowingcommand:
$ lsb_release -a
No LSB modules are available.
Distributor ID: Ubuntu
Description: Ubuntu 18.04.1 LTS
Release: 18.04
Codename: bionic
LookattheversionnumbernexttoRelease intheconsoleoutput,and
followthecorrespondinginstructionsbelow.
38
2.4. Ubuntu Linux
Ubuntu 18.04 or Greater
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
commandsintheTerminalapplication:
$ sudo apt-get update
$
sudo apt-get install python3.9 idle-python3.9 python3-pip
Note that because the Universe repository is usually behind the
Pythonreleaseschedule,youmaynotgetthelatestversionofPython
3.9. However,anyversionofPython3.9willworkforthisbook.
Ubuntu 17 and Lower
For Ubuntu versions 17 and lower, Python 3.9 is not in the Universe
repository. YouneedtogetitfromaPersonalPackageArchive(PPA).
To install Python from the
deadsnakes PPA, run the following com-
mandsintheTerminalapplication:
$ sudo add-apt-repository ppa:deadsnakes/ppa
$ sudo apt-get update
$
sudo apt-get install python3.9 idle-python3.9 python3-pip
YoucancheckthatthecorrectversionofPythonwasinstalledbyrun-
ningpython3 --version. Ifyouseeaversionnumberlessthan3.9,then
you may need to type python3.9 --version. Now you can open IDLE
andgetreadytowriteyourfirstPythonprogram.
Open IDLE
YoucanopenIDLEfromthecommandlinebytypingthefollowing:
$ idle-python3.9
39
2.4. Ubuntu Linux
On some Linux installations, you can open IDLE with the following
shortenedcommand:
$ idle3
IDLEopensaPython shell inanewwindow. ThePythonshellisan
interactive environment that allows you to type in Python code and
executeitimmediately. It’sagreatwaytogetstartedwithPython!
Note
While you’re free to use a code editor other than IDLE if you
prefer, note that some chapters, especially chapter 7, “Finding
andFixingCodeBugs,”docontainmaterialspecifictoIDLE.
ThePythonshellwindowlookslikethis:
At the top of the window, you can see the version of Python that is
runningandsomeinformationabouttheoperatingsystem. Ifyousee
a version less than 3.9, then you may need to revisit the installation
instructionsintheprevioussection.
40
2.4. Ubuntu Linux
Important
IfyouopenIDLEwiththeidle3 commandandseeaversionless
than3.9displayedinthePythonshellwindow,thenyou’llneed
toopenIDLEwiththeidle-python3.9 command.
The >>> symbol that you see in the IDLE window is called a prompt.
Wheneveryouseethis,itmeansthatPythoniswaitingforyoutogive
itsomeinstructions.
Interactive Quiz
This chapter comes with a free online quiz to check your learn-
ingprogress. Youcanaccessthequizusingyourphoneorcom-
puteratthefollowingwebaddress:
realpython.com/quizzes/pybasics-setup
NowthatyouhavePythoninstalled,let’sgetstraightintowritingyour
firstPythonprogram! Goaheadandmoveontochapter3.
41
Chapter 3
Your First Python Program
NowthatyouhavethelatestversionofPythoninstalledonyourcom-
puter,it’stimetostartcoding!
In this chapter, you will:
WriteyourfirstPythonprogram
Learnwhathappenswhenyourunaprogramwithanerror
Learnhowtodeclareavariableandinspectitsvalue
Learnhowtowritecomments
ReadytobeginyourPythonjourney? Let’sgo!
42
3.1. Write a Python Program
3.1 Write a Python Program
Ifyoudon’talreadyhaveIDLEopen,thengoaheadandopenit. There
aretwomainwindowsthatyou’llworkwithinIDLE:theinteractive
window, which is the one that opens when you start IDLE, and the
editor window.
Youcantypecodeintoboththeinteractivewindowandtheeditorwin-
dow. Thedifferencebetweenthetwowindows is in how theyexecute
code. In this section, you’ll learnhowto execute Python code in both
windows.
The Interactive Window
IDLE’s interactive window contains a Python shell, which is a tex-
tualuserinterfaceusedtointeractwiththePythonlanguage. Youcan
typea bitofPythoncodeintotheinteractivewindowandpress
Enter
toimmediatelyseetheresults. Hencethenameinteractive window.
The interactive window opens automatically when you start IDLE.
You’ll see the following text, with some minor differences depending
onyoursetup,displayedatthetopofthewindow:
Python 3.9.0 (tags/v3.9.0:1b293b6)
[MSC v.1916 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>>
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’lltypeinyourcode.
43
3.1. Write a Python Program
Goaheadandtype1 + 1 atthepromptandpress
Enter
:
>>> 1 + 1
2
>>>
Pythonevaluatestheexpression,displaystheresult(2),thendisplays
anotherprompt. Everytimeyourunsomecodeintheinteractivewin-
dow,anewpromptappearsdirectlybelowtheresult.
ExecutingPythonintheinteractivewindowcanbedescribedasaloop
withthreesteps:
1. Pythonreads thecodeenteredattheprompt.
2. Pythonevaluates thecode.
3. Pythonprints theresultandwaitsformoreinput.
This loop is commonly referred to as a read-evaluate-print loop and
isabbreviatedasREPL.Pythonprogrammerssometimesrefertothe
PythonshellasthePythonREPL,orjust“theREPL”forshort.
Let’s try something a little more interesting than adding numbers. A
riteofpassageforeveryprogrammer iswritingaprogramthatprints
thephrase“Hello,World”onthescreen.
Atthepromptintheinteractivewindow,typethewordprint followed
byasetofparentheseswiththetext"Hello, World" inside:
>>> print("Hello, World")
Hello, World
44
3.1. Write a Python Program
A function iscodethat performs some task and can be invokedbya
name. Theabovecodeinvokes,orcalls,theprint() functionwiththe
text"Hello, World" asinput.
TheparenthesestellPython tocalltheprint() function. They also en-
closeeverythingthatgetssenttothefunctionasinput. Thequotation
marks indicate that "Hello, World" really is text and not something
else.
Note
IDLE highlights parts of your code in different colors as you
typetomakeiteasierforyoutoidentifythedifferentparts.
Bydefault,functionsarehighlightedinpurpleandtextishigh-
lightedingreen.
The interactive window executes a single line of code at a time. This
isusefulfortryingoutsmallcodeexamplesandexploringthePython
language, but it has a major limitation: you have to enter your code
onelineatatime!
Alternatively,youcansavePythoncodeinatextleandexecuteallof
thecodeinthefiletorunanentireprogram.
The Editor Window
You’ll write your Python files using IDLE’s editor window. You can
opentheeditorwindowbyselecting
File New File
fromthemenuat
thetopoftheinteractivewindow.
Theinteractivewindowstaysopenwhenyouopentheeditorwindow.
Itdisplaystheoutputgeneratedbycodeintheeditorwindow,soyou’ll
wanttoarrangethetwowindowssothatyoucanseethembothatthe
sametime.
45
3.1. Write a Python Program
Intheeditorwindow,typeinthesamecodeyouusedtoprint"Hello,
World" intheinteractivewindow:
print("Hello, World")
IDLE highlights code typed into the editor window just like in the in-
teractivewindow.
Important
WhenyouwritecodeinaPythonfile,youdon’tneedtoinclude
the>>> prompt.
Before you run your program, you need to save it. Select
File Save
fromthemenuandsavethefileashello_world.py.
Note
Onsomesystems,thedefaultdirectoryforsavingfilesinIDLE
is the Python installation directory. Do not save your files to
thisdirectory. Instead,savethemtoyourdesktoportoafolder
inyouruser’shomedirectory.
The .py extension indicates that a file contains Python code. In fact,
saving your file with any other extension removes the code highlight-
ing. IDLEonlyhighlightsPythoncodewhenit’sstoredina.py file.
Running Python Programs in the Editor Window
To run your program, select
Run Run Module
from the menu in the
editorwindow.
Note
Pressing
F5
alsorunsaprogramfromtheeditorwindow.
Programoutputalwaysappearsintheinteractivewindow.
46
3.2. Mess Things Up
Every time you run code from a file, you’ll see something like the fol-
lowingoutputintheinteractivewindow:
>>> =================== RESTART ===================
IDLErestartsthePythoninterpreter,whichisthecomputerprogram
thatactuallyexecutesyourcode,everytimeyourunafile. Thismakes
surethatprogramsareexecutedthesamewayeachtime.
Opening Python Files in the Editor 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
editorwindow,soyoucanhaveseveralfilesopenatthesametime.
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
toopenthefileinIDLE’seditorwindow.
Double-clicking on a .py file from a file manager executes the pro-
gram. However, this usually runs the file with the system Python,
and the program window disappears immediately after the program
terminates—oftenbeforeyoucanevenseeanyoutput.
For now, the best way to run your Python programs is to open them
inIDLE’seditorwindowandrunthemfromthere.
3.2 Mess Things Up
Everybody makes mistakes—especially while programming! In case
you haven’t made any mistakes yet, let’s get a head start and mess
somethinguponpurposetoseewhathappens.
Mistakes in programs are called errors. You’ll experience two main
typesoferrors: syntaxerrorsandruntimeerrors.
47
3.2. Mess Things Up
Syntax Errors
A syntax error occurswhen you write code thatisn’t allowed in the
Pythonlanguage.
Let’s create a syntax error by removing the last quotation mark from
thecodeinthehello_world.py filethatyoucreatedinthelastsection:
print("Hello, World)
Save the file and press
F5
to run it. The code won’t run! IDLE dis-
playsanalertboxwiththefollowingmessage:
EOL while scanning string literal.
Therearetwotermsinthismessagethatmaybeunfamiliar:
1. A string literal is text enclosed in quotation marks. "Hello,
World" isastringliteral.
2. EOL standsforendof line.
So, the message tells you that Python got to the end of a line while
readingastringliteral. String literalsmustbeterminatedwitha quo-
tationmarkbeforetheendofaline.
IDLEhighlightsthelinecontainingprint("Hello, World) inredtohelp
you quickly find the line of code with the syntax error. Without the
second quotation mark, everything after the first quotation mark—
includingtheclosingparenthesis—ispartofastringliteral.
Runtime Errors
IDLE catches syntax errors before a program starts running. In con-
trast,runtime errors only occur while a program is running.
To generate a runtime error, remove both quotation marks in the
hello_world.py file:
48
3.2. Mess Things Up
print(Hello, World)
Didyounoticehowthetextcolorchangedtoblackwhenyouremoved
the quotation marks? IDLE no longer recognizes Hello, World as text.
Whatdoyouthinkwillhappenwhenyouruntheprogram? Press
F5
tofindout!
Thefollowingtextdisplaysinredintheinteractivewindow:
Traceback (most recent call last):
File "/home/hello_world.py", line 1, in <module>
print(Hello, World)
NameError: name 'Hello' is not defined
Whenever an error occurs, Python stops executing the program and
displaysseverallinesoftextcalledatraceback. Thetracebackshows
usefulinformationabouttheerror.
Tracebacksarebestreadfromthebottomup:
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
nameHello isnotdefinedanywhere.
Thesecondtolastlineshowsyouthecodethatproducedtheerror.
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
largerfiles.
Thethirdtolastlinetellsyouthenameofthefileandthelinenum-
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
syntaxerrorsandruntimeerrorsbyworkingonthereviewexercises.
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. WriteaprogramthatIDLEwon’trunbecauseithasasyntaxerror.
2. Writeaprogramthatcrashesonlywhileit’srunningbecauseithas
aruntimeerror.
3.3 Create a Variable
InPython,variables arenamesthatcanbeassignedavalueandthen
usedtorefertothatvaluethroughoutyourcode.
Variablesarefundamentaltoprogrammingfortworeasons:
1. Variables keep values accessible: For example, you can as-
signtheresultofsome time-consuming operation toavariableso
thatyourprogramdoesn’thavetoperformtheoperationeachtime
youneedtousetheresult.
2. Variables give values context: Thenumber28 couldmeanlots
of different things, such as the number of students in a class, the
number of times a user has accessed a website, and so on. Giving
the value 28 a name like num_students makes the meaning of the
valueclear.
Inthissection,you’lllearnhowtousevariablesinyourcode,aswellas
some of the conventions Python programmers follow when choosing
namesforvariables.
The Assignment Operator
An operator is a symbol, such as +, that performs an operation on
one or more values. For example, the + operator takes two numbers,
one to the left of the operator and one to the right, and adds them
together.
50
3.3. Create a Variable
Values are assigned to variable names using a special symbol called
theassignment operator (=). The= operatortakesthevaluetothe
rightoftheoperatorandassignsittothenameontheleft.
Let’smodifythehello_world.py filefromtheprevioussectiontoassign
sometextinavariablebeforeprintingittothescreen:
>>> greeting = "Hello, World"
>>> print(greeting)
Hello, world
Onthefirstline,youcreateavariablenamedgreeting andassignitthe
value"Hello, World" usingthe= operator.
print(greeting) displaystheoutputHello, World becausePythonlooks
for the name greeting, finds that it’s been assigned the value "Hello,
World", and replaces the variable name with its value before calling
thefunction.
If you hadn’t executed greeting = "Hello, World" before executing
print(greeting), then you would have seen a NameError like you did
whenyoutriedtoexecuteprint(Hello, World) intheprevioussection.
Note
Although= looksliketheequalssignfrommathematics,ithasa
differentmeaninginPython. This distinctionisimportantand
canbeasourceoffrustrationforbeginnerprogrammers.
Justremember,wheneveryouseethe= operator,whateveristo
therightofitisbeingassignedtoavariableontheleft.
Variable names are case sensitive, so a variable named greeting is
notthesameasavariablenamedGreeting. Forinstance,thefollowing
codeproducesaNameError:
51
3.3. Create a Variable
>>> greeting = "Hello, World"
>>> print(Greeting)
Traceback (most recent call last):
File
"<stdin>", line 1, in <module>
NameError: name 'Greeting' is not defined
If you have trouble with an example in this book, double-check that
everycharacterinyourcode—includingspaces—matchestheexample
exactly. Computers have no common sense, so being almost correct
isn’tgoodenough!
Rules for Valid Variable Names
Variable names can be as long or as short as you like, but there are a
few rules that you must follow. Variable names may contain upper-
case and lowercase letters (A–Z, a–z), digits (0–9), and underscores
(_),buttheycannotbeginwithadigit.
Forexample,eachofthefollowingisavalidPythonvariablename:
string1
_a1p4a
list_of_names
The following aren’t valid variable names because they start with a
digit:
9lives
99_balloons
2beOrNot2Be
In addition to English letters and digits, Python variable names may
containmanydifferentvalidUnicodecharacters.
Unicode is a standard for digitally representing characters used in
most of the world’s writing systems. That means variable names can
containlettersfromnon-English alphabets, suchasdecoratedletters
52
3.3. Create a Variable
likeéandü,andevenChinese,Japanese,andArabicsymbols.
However,noteverysystemcandisplaydecoratedcharacters, so it’s a
goodideatoavoidthemifyou’regoingtoshareyourcodewithpeople
indifferentregions.
Note
You’lllearnmoreaboutUnicodeinchapter12.
You can also read about Python’s
support for Unicode in the
officialPythondocumentation.
Just because a variable name is valid doesn’t necessarily mean that
it’sagoodname.
Choosingagoodnameforavariablecanbesurprisinglydifficult. For-
tunately, there are some guidelines that you can follow to help you
choosebetternames.
Descriptive Names Are Better Than Short Names
Descriptive variable names are essential, especially for complex
programs. Writing descriptive names often requires using multiple
words. Don’tbeafraidtouselongvariablenames.
Inthefollowingexample,thevalue3600 isassignedtothevariables:
s = 3600
Thenames istotallyambiguous. Usingafullwordmakesitaloteasier
tounderstandwhatthecodemeans:
seconds = 3600
53
3.3. Create a Variable
seconds is a bettername than s because it provides more context. But
itstilldoesn’tconveythefullmeaningofthecode. Is3600 thenumber
ofsecondsittakesforaprocesstofinish,orisitthelengthofamovie?
There’snowaytotell.
Thefollowingnameleavesnodoubtaboutwhatthecodemeans:
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
clarityismassive.
Althoughnamingvariablesdescriptivelymeans usinglongervariable
names, you should avoid using excessively long names. A good rule
ofthumbistolimitvariablenamestothreeorfourwordsmaximum.
Python Variable Naming Conventions
In many programming languages, it’s common to write variable
names in mixedCase. In this system, you capitalize the first letter
of every word except the first and leave all other letters in lowercase.
Forexample,numStudents andlistOfNames arewritteninmixedCase.
In Python, however, it’s more common to write variable names in
lower_case_with_underscores. In this system, you leave every
letter in lowercase and separate each word with an underscore. For
instance, both num_students and list_of_names are written using the
lower_case_with_underscoressystem.
There’s no rule mandating that you write your variable names in
lower_case_with_underscores. The practice is codified, though, in a
document called
PEP 8, which is widely regarded as the official style
guideforwritingPython.
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
featurestothelanguage.
Following the standards outlined in PEP 8 ensures that your Python
code is readable by most Python programmers. This makes sharing
codeandcollaboratingwithotherpeopleeasierforeveryoneinvolved.
Review Exercises
You can nd the solutions to these exercises and many other bonus
resources online at realpython.com/python-basics/resources
1. Usingtheinteractivewindow,displaysometextusing print().
2. Using the interactive window, assign a string literal to a variable.
Thenprintthecontentsofthevariableusingtheprint() function.
3. Repeatthefirsttwoexercisesusingtheeditorwindow.
3.4 Inspect Values in the Interactive
Window
TypethefollowingintoIDLE’sinteractivewindow:
>>> greeting = "Hello, World"
>>> greeting
'Hello, World'
When you press
Enter
after typing greeting a second time, Python
prints the string literal assigned to greeting even though you didn’t
usetheprint() function. Thisiscalledvariable inspection.
55
3.4. Inspect Values in the Interactive Window
Nowprintthestringassignedtogreeting usingtheprint() 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
andpressing
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.
Youassignedthestringliteral"Hello, World" togreeting,whichiswhy
'Hello, World' isdisplayedwithquotationmarks.
Note
String literals can be created with single or double quotation
marks in Python. At Real Python, we use double quotes wher-
everpossible,whereasIDLEoutputappearsinsinglequotesby
default.
Both "Hello, World" and 'Hello, World' mean the same thing in
Python—what’smostimportantisthatyoubeconsistentinyour
usage. You’lllearnmoreaboutstringsinchapter4.
Ontheotherhand,print() displaysamorehuman-readablerepresen-
tation of the variable’s value which, for string literals, means display-
ingthetextwithoutquotationmarks.
Sometimes,bothprintingandinspectingavariableproducethesame
output:
>>> x = 2
>>> x
2
>>> print(x)
2
56
3.4. Inspect Values in the Interactive Window
Here,youassignthenumber2 tox. Bothusingprint(x) andinspecting
x display output without quotation marks because 2 is a number and
not text. In most cases, though, variable inspection gives you more
usefulinformationthanprint().
Suppose you have two variables: x, which is assigned the number 2,
and y, which is assigned the string literal "2". In this case, print(x)
andprint(y) bothdisplaythesamething:
>>> x = 2
>>> y = "2"
>>> print(x)
2
>>> print(y)
2
However, inspecting x and y shows the difference between each vari-
able’svalue:
>>> x
2
>>> y
'2'
The key takeaway here is that print() displays a readable representa-
tionofa variable’s value, whilevariableinspection displays the value
asitappearsinthecode.
Keep in mind that variable inspection works only in the interactive
window. For example, try running the following program from the
editorwindow:
greeting = "Hello, World"
greeting
The program executes without any errors, but it doesn’t display any
output!
57
3.5. Leave Yourself Helpful Notes
3.5 Leave Yourself Helpful Notes
Programmers sometimes read code they wrote a while ago and won-
der,“Whatdoesthisdo?” Whenyouhaven’tlookedatcodeinawhile,
itcanbedifficulttorememberwhyyouwroteitthewayyoudid!
To help avoid this problem, you can leave comments in your code.
Comments arelinesoftextthatdon’taffectthewayaprogramruns.
Theydocumentwhatcodedoesorwhytheprogrammermadecertain
decisions.
How to Write a Comment
The most common way to write a comment is to begin a new line in
your code with the # character. When you run your code, Python ig-
noreslinesstartingwith#.
Commentsthatstartonanewlinearecalledblock comments. You
can also write inline comments, which are comments that appear
onthesame line as the code they reference. Justputa # attheend of
thelineofcode,followedbythetextinyourcomment.
Here’sanexampleofaprogramwithbothkindsofcomments:
# This is a block comment.
greeting = "Hello, World"
print(greeting) # This is an inline comment.
Ofcourse, you can stilluse the # symbolinside a string. For instance,
Pythonwon’tmistakethefollowingforthestartofacomment:
>>> print("#1")
#1
Ingeneral,it’sagoodideatokeepcommentsasshortaspossible,but
sometimesyouneedtowritemorethanreasonablyfitsonasingleline.
In that case, you can continue your comment on a new line that also
beginswiththe# symbol:
58
3.5. Leave Yourself Helpful Notes
# This is my first program.
# It prints the phrase "Hello, World"
# The comments are longer than the code!
greeting = "Hello, World"
print(greeting)
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-
tuallydeletethecode.
TocommentoutasectionofcodeinIDLE,highlightoneormorelines
tobecommentedandpress:
Windows:
Alt
+
3
macOS:
Ctrl
+
3
Ubuntu Linux:
Ctrl
+
D
Toremovecomments,highlightthecommentedlinesandpress:
Windows:
Alt
+
4
macOS:
Ctrl
+
4
Ubuntu Linux:
Ctrl
+
Shift
+
D
Nowlet’slookatsomecommonconventionsforcodecomments.
Conventions and Pet Peeves
Accordingto
PEP8,comments should always be written in complete
sentences with a single space between the # and the first word of the
comment:
# This comment is formatted to PEP 8.
#this one isn't
Forinlinecomments,PEP8recommendsatleasttwospacesbetween
59
3.6. Summary and Additional Resources
thecodeandthe# symbol:
phrase = "Hello, World" # This comment is PEP 8 compliant.
print(phrase)# This comment isn't.
PEP 8 recommends that comments be used sparingly. A major pet
peeveamongprogrammersiscommentsthatdescribewhatisalready
obviousfromreadingthecode.
Forexample,thecommentinthefollowingcodeisunnecessary:
# Print "Hello, World"
print("Hello, World")
The comment is unnecessary because the code itself explicitly de-
scribes what’s happening. Comments are best used to clarify code
that may be difficult to understand or to explain why something is
codedacertainway.
3.6 Summary and Additional Resources
In this chapter, you wrote and executed your first Python program!
Youwroteasmallprogramthat displays the text "Hello, World" using
theprint() function.
Thenyou learnedaboutsyntax errors,whichoccurbefore IDLEex-
ecutes a program that contains invalid Python code, and runtime
errors,whichonlyoccurwhile aprogramisrunning.
You saw how to assign values to variables using the assignment
operator (=)andhowtoinspectvariablesintheinteractivewindow.
Finally,youlearnedhowtowritehelpfulcomments inyourcodefor
whenyouorsomeoneelselooksatitinthefuture.
60
3.6. Summary and Additional Resources
Interactive Quiz
This chapter comes with a free online quiz to check your learn-
ingprogress. Youcanaccessthequizusingyourphoneorcom-
puteratthefollowingwebaddress:
realpython.com/quizzes/pybasics-first-program
Additional Resources
Tolearnmore,checkoutthefollowingresources:
“11BeginnerTipsforLearningPythonProgramming”
“WritingCommentsinPython(Guide)”
For links and additional resources to further deepen your Python
skills, visit realpython.com/python-basics/resources
61
Chapter 4
Strings and String Methods
Many programmers, regardless of their specialty, deal with text on a
daily basis. For example, web developers work with text input from
web forms. Data scientists process text to extract data and perform
tasks like sentiment analysis, which can help identify and classify
opinionsinabodyoftext.
Collections of text in Python are called strings. Special functions
called string methods are used to manipulate strings. There are
stringmethodsforchangingastringfromlowercasetouppercase,re-
moving whitespace from the beginning or end of a string, replacing
partsofastringwithdifferenttext,andmuchmore.
In this chapter, you’ll learn how to:
Manipulatestringswithstringmethods
Workwithuserinput
Dealwithstringsofnumbers
Formatstringsforprinting
Let’sgetstarted!
62
4.1. What Is a String?
4.1 What Is a String?
In chapter 3, you created the string "Hello, World" and printed it in
IDLE’s interactive window using print(). In this section, you’ll get a
deeperlookintoexactlywhatstringsareandthevariouswaysyoucan
createtheminPython.
The String Data Type
StringsareoneofthefundamentalPythondatatypes. Thetermdata
type refers to what kind of data a value represents. Strings are used
torepresenttext.
Note
ThereareseveralotherdatatypesbuiltintoPython. Forexam-
ple, you’ll learn about numerical data types in chapter 5 and
Booleandatatypesinchapter8.
Wesaythatstringsareafundamental data type becausetheycan’t
be broken down into smaller values of a different type. Not all data
typesarefundamental. You’ll learn about compound data types, also
knownasdata structures, in chapter 9.
The string data type has a special abbreviated name in Python: str.
Youcanseethisbyusingtype(),whichisafunctionusedtodetermine
thedatatypeofagivenvalue.
TypethefollowingintoIDLE’sinteractivewindow:
>>> type("Hello, World")
<class 'str'>
The output <class 'str'> indicates that the value "Hello, World" is an
instanceofthestr datatype. Thatis,"Hello, World" isastring.
63
4.1. What Is a String?
Note
Fornow,youcanthinkofthewordclass asasynonymfordata
type, although it actually refers to something more specific.
You’llseejustwhataclassisinchapter10.
type() alsoworksforvaluesthathavebeenassignedtoavariable:
>>> phrase = "Hello, World"
>>> type(phrase)
<class 'str'>
Stringshavethreeimportantproperties:
1. Stringscontainindividuallettersorsymbolscalledcharacters.
2. Strings have a length, defined as the number of characters the
stringcontains.
3. Characters in a string appear in a sequence, which means that
eachcharacterhasanumberedpositioninthestring.
Let’stakeacloserlookathowstringsarecreated.
String Literals
As you’ve already seen, you can create a string by surrounding some
textwithquotationmarks:
string1 = 'Hello, World'
string2 = "1234"
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
andendofthestring.
Whenever you create a string by surrounding text with quotation
marks, the string is called a string literal. The name indicates that
the string is literally written out in your code. All the strings you’ve
seenthusfararestringliterals.
64
4.1. What Is a String?
Note
Notevery string is a string literal. Sometimes strings areinput
by a user or read from a file. Since they’re not typed out with
quotationmarksinyourcode,they’renotstringliterals.
The quotes surrounding a string are called delimiters because they
tellPythonwhereastringbeginsandwhereitends. Whenonetypeof
quotes is used as the delimiter, the other type can be used inside the
string:
string3 = "We're #1!"
string4 = 'I said, "Put it over by the llama."'
After Python reads the first delimiter, it considers all the characters
afteritpartof the string until it reaches a second matching delimiter.
Thisiswhyyoucan use a singlequoteinastringdelimitedbydouble
quotes,andviceversa.
If you try to use double quotes inside a string delimited by double
quotes,you’llgetanerror:
>>> text = "She said, "What time is it?""
File "<stdin>", line 1
text = "She said, "What time is it?""
^
SyntaxError: invalid syntax
PythonthrowsaSyntaxError becauseitthinksthestringendsafterthe
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-
sideastring,thenyoucanescape thecharacterusingabackslash:
>>> text = "She said, \"What time is it?\""
>>> print(text)
She said,
"What time is it?"
65
4.1. What Is a String?
Note
When you work on a project, it’s a good idea to use only single
quotesoronlydoublequotestodelimiteverystring.
Keepinmindthattherereallyisn’tarightorwrongchoice! The
goal is to be consistent because consistency helps make your
codeeasiertoreadandunderstand.
Strings can contain any valid Unicode character. For example, the
string"We're #1!" containsthepoundsign(#)and"1234" containsnum-
bers. "×Pýŧħøŋ×" isalsoavalidPythonstring!
Determine the Length of a String
The number of characters contained in a string, including spaces, is
called the length of the string. For example, the string "abc" has a
lengthof 3, and the string "Don't Panic" hasalengthof 11.
Pythonhasabuilt-inlen() functionthatyoucanusetodeterminethe
lengthofastring. Toseehowitworks,typethefollowingintoIDLE’s
interactivewindow:
>>> len("abc")
3
Youcanalsouselen() to get thelengthofastringthat’sassignedto a
variable:
>>> letters = "abc"
>>> len(letters)
3
First,youassignthestring"abc" tothevariableletters. Thenyouuse
len() togetthelengthof letters,whichis3.
66
4.1. What Is a String?
Multiline Strings
The
PEP8styleguiderecommendsthateachlineofPythoncodecon-
tainnomorethanseventy-ninecharacters—includingspaces.
Note
PEP 8’s seventy-nine-character line length is a recommenda-
tion, not a rule. Some Python programmers prefer a slightly
longerlinelength.
In this book, we’ll strictly follow PEP 8’s recommended line
length.
Whether you follow PEP 8 or choose a longer line length, sometimes
you’llneedtocreatestringliteralswithmorecharactersthanyourcho-
senlimit.
Todealwithlongstrings,youcanbreakthemupacrossmultiplelines
into multiline strings. For example, suppose you need to fit the
followingtextintoastringliteral:
This planet has—or rather had—a problem, which was
this: most of the people living on it were unhappy for
prettymuchofthetime. Many solutionsweresuggested
for this problem, but most of these were largely con-
cerned with the movements of small green pieces of
paper, which is odd because on the whole it wasn’t the
smallgreenpiecesofpaperthatwereunhappy.
DouglasAdams,The Hitchhiker’s Guide to the Galaxy
This paragraph contains far more than seventy-nine characters, so
any line of code containing the paragraph as a string literal violates
PEP8. So,whatdoyoudo?
Thereareacoupleofwaystotacklethis. Onewayistobreakthestring
upacrossmultiplelinesandputabackslash(\)attheendofallbutthe
67
4.1. What Is a String?
lastline. TobePEP8compliant,thetotallengthoftheline,including
thebackslashes,mustbeseventy-ninecharactersorfewer.
Here’s how you could write the paragraph as a multiline string using
thebackslashmethod:
paragraph = "This planet has—or rather had—a problem, which was \
this: most of the people living on it were unhappy for pretty much \
of the time. Many solutions were suggested for this problem, but \
most of these were largely concerned with the movements of small \
green pieces of paper, which is odd because on the whole it wasn't \
the small green pieces of paper that were unhappy."
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
thatyoudidn’tclosethestringwithamatchingdoublequote. Witha
backslashattheend,youcankeepwritingthesamestringonthenext
line.
When you print() a multiline string that’s broken up by backslashes,
theoutputisdisplayedonasingleline:
>>> long_string = "This multiline string is \
displayed on one line"
>>> print(long_string)
This multiline string is displayed on one line
Youcanalsocreatemultilinestringsusingtriplequotes(""" or''')as
delimiters. Here’showtowritealongparagraphusingthisapproach:
paragraph = """This planet has—or rather had—a problem, which was
this: most of the people living on it were unhappy for pretty much
of the time. Many solutions were suggested for this problem, but
most of these were largely concerned with the movements of small
green pieces of paper, which is odd because on the whole it wasn't
the small green pieces of paper that were unhappy."""
68
4.2. Concatenation, Indexing, and Slicing
Triple-quoted strings preserve whitespace, including newlines. This
meansthatrunningprint(paragraph) woulddisplay the string on mul-
tiplelines,justas itappearsinthestring literal. Thismayormaynot
be what you want, so you’ll need to think about the desired output
beforeyouchoosehowtowriteamultilinestring.
Toseehowwhitespaceispreservedinatriple-quotedstring,typethe
followingintoIDLE’sinteractivewindow:
>>> print("""An example of a
... string that spans across multiple lines
... and also preserves whitespace."""
)
An example of a
string that spans across multiple lines
and also preserves whitespace.
Notice how the second and third lines in the output are indented in
exactlythesamewayasthestringliteral.
Review Exercises
You can nd the solutions to these exercises and many other bonus
resources online at
realpython.com/python-basics/resources
1. Printastringthatusesdoublequotationmarksinsidethestring.
2. Printastringthatusesanapostropheinsidethestring.
3. Printastringthatspansmultiplelineswithwhitespacepreserved.
4. Printa string that iscoded on multiple lines butgets printed on a
singleline.
4.2 Concatenation, Indexing, and
Slicing
Nowthat you know whata string is and how to declarestring literals
inyourcode,let’sexploresomeofthethingsyoucandowithstrings.
69
4.2. Concatenation, Indexing, and Slicing
Inthissection,you’lllearnaboutthreebasicstringoperations:
1. Concatenation,whichjoinstwostringstogether
2. Indexing,whichgetsasinglecharacterfromastring
3. Slicing,whichgetsseveralcharactersfromastringatonce
Let’sdivein!
String Concatenation
Youcancombine,orconcatenate,twostringsusingthe+ operator:
>>> string1 = "abra"
>>> string2 = "cadabra"
>>> magic_string = string1 + string2
>>> magic_string
'abracadabra'
Inthisexample,thestringconcatenationoccursonthethirdline. You
concatenate string1 and string2 using +, and then you assign the re-
sulttothevariablemagic_string. Noticethatthetwostringsarejoined
withoutanywhitespacebetweenthem.
You can use string concatenation to join two related strings, such as
joiningafirstnameandalastnameintoafullname:
>>> first_name = "Arthur"
>>> last_name = "Dent"
>>> full_name = first_name + " " + last_name
>>> full_name
'Arthur Dent'
Here, you use string concatenation twice on the same line. First, you
concatenate first_name with " " to ensure a space appears after the
firstnameinthefinalstring. Thisproducesthestring"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.
Youcanaccessthecharacteratthenthpositionbyputtingthenumber
n betweentwosquarebrackets([])immediatelyafterthestring:
>>> flavor = "fig pie"
>>> flavor[1]
'i'
flavor[1] returnsthecharacteratposition1 in"fig pie",whichisi.
Wait. Isn’tf thefirstcharacterof "fig pie"?
In Python—and in most other programming languages—counting al-
ways starts at zero. To get the character at the beginning of a string,
youneedtoaccessthecharacteratposition0:
>>> flavor[0]
'f'
Important
Forgetting that counting starts with zero and trying to access
thefirst character in a string withthe index 1 results in an o-
by-one error.
Off-by-oneerrorsareacommonsourceoffrustrationforbegin-
ningandexperiencedprogrammersalike!
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
raisesanIndexError:
>>> flavor[9]
Traceback (most recent call last):
File
"<pyshell#4>", line 1, in <module>
flavor[9]
IndexError: string index out of range
Thelargestindexinastringisalwaysonelessthanthestring’slength.
Since"fig pie" hasalengthofseven,thelargestindexallowedis 6.
Stringsalsosupportnegativeindices:
>>> flavor[-1]
'e'
The last character in a string has index -1, which for "fig pie" is the
lettere. Thesecondtolastcharacteri hasindex-2,andsoon.
The following figure shows the negative index for each character in
thestring"fig pie":
| f | i | g | | p | i | e |
-7 -6 -5 -4 -3 -2 -1
Justlikewithpositiveindices,PythonraisesanIndexError ifyoutryto
accessanegativeindexlessthantheindexofthefirstcharacterinthe
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
abetterchoicethanapositiveindex.
72
4.2. Concatenation, Indexing, and Slicing
For example, suppose a string input by a user is assigned to the vari-
ableuser_input. Ifyouneedtogetthelastcharacterofthestring,how
doyouknowwhatindextouse?
One way to get the last character of a string is to calculate the final
indexusinglen():
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’trequireanintermediatesteptocalculatethefinalindex:
last_character = user_input[-1]
String Slicing
Supposeyouneed astringcontainingjustthe firstthreelettersofthe
string "fig pie". You could access each character by index and con-
catenatethemlikethis:
>>> first_three_letters = flavor[0] + flavor[1] + flavor[2]
>>> first_three_letters
'fig'
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
thiswithmuchlesstyping.
Youcanextractaportionofastring,calledasubstring,byinserting
a colon between two index numbers set inside square brackets like
this:
>>> flavor = "fig pie"
>>> flavor[0:3]
'fig'
73
4.2. Concatenation, Indexing, and Slicing
flavor[0:3] returns the first three characters of the string assigned to
flavor,startingwiththecharacteratindex0 andgoinguptobutnotin-
cludingthecharacteratindex3. The[0:3] partof flavor[0:3] iscalled
aslice. Inthiscase,itreturnsasliceof "fig pie". Yum!
String slices can be confusing because the substring returned by
the slice includes the character whose index is the first number but
doesn’tincludethecharacterwhoseindexisthesecondnumber.
To remember how slicing works, you can think of a string as a se-
quence of square slots. The left and right boundaries of each slot are
numbered sequentially from zero up to the length of the string, and
eachslotisfilledwithacharacterinthestring.
Here’swhatthislookslikeforthestring"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] returnsthestring" pie".
Ifyouomitthefirstindexinaslice,thenPythonassumesyouwantto
startatindex0:
>>> flavor[:3]
'fig'
Theslice[:3] isequivalenttotheslice[0:3],soflavor[:3] returnsthe
firstthreecharactersinthestring"fig pie".
Similarly, if you omit the second index in the slice, then Python as-
sumesyouwanttoreturnthesubstringthatbeginswiththecharacter
74
4.2. Concatenation, Indexing, and Slicing
whoseindexisthefirstnumberinthesliceandendswiththelastchar-
acterinthestring:
>>> 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
startswiththespaceandendswiththelastletter: " 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
theentirestring:
>>> flavor[:]
'fig pie'
It’simportant to note that, unlike with stringindexing, Python won’t
raise an IndexError when you try to slice between boundaries that fall
outsidethebeginningorendingboundariesofastring:
>>> 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-
turnstheentirestring"fig pie".
Thethirdlineshowswhathappenswhenyoutrytogetasliceinwhich
the entire range is out of bounds. flavor[13:15] attempts to get the
thirteenth and fourteenth characters, which don’t exist. Instead of
raisinganerror,Pythonreturnstheempty string ("").
75
4.2. Concatenation, Indexing, and Slicing
Note
Theemptystringiscalledemptybecauseitdoesn’tcontainany
characters. You can create it by writing two quotation marks
withnothingbetweenthem:
empty_string = ""
Astringwithanythinginit—evenaspace—isnotempty. Allthe
followingstringsarenon-empty:
non_empty_string1 = " "
non_empty_string2 = " "
non_empty_string3 = " "
Even though these strings don’t contain any visible characters,
theyarenon-emptybecausetheydocontainspaces.
Youcanusenegativenumbersinslices. Therulesforsliceswithnega-
tivenumbersareexactly the same as the rules for sliceswithpositive
numbers. It helps to visualize the string as slots with the boundaries
labeledwithnegativenumbers:
| f | i | g | | p | i | e |
-7 -6 -5 -4 -3 -2 -1
Justlikebefore, 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]
returnsthefirstthreelettersofthestring"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
seemtobethenumber0,butthatdoesn’twork.
76
4.2. Concatenation, Indexing, and Slicing
Insteadofreturningtheentirestring,[-7:0] returnstheemptystring:
>>> flavor[-7:0]
''
This happens because the second number in a slice must correspond
toaboundarythatistotherightoftheboundarycorrespondingtothe
first number, but both -7 and 0 correspond to the leftmost boundary
inthefigure.
Ifyouneedtoincludethefinalcharacterofastringinyourslice,then
youcanomitthesecondnumber:
>>> flavor[-7:]
'fig pie'
Ofcourse,usingflavor[-7:] togettheentirestringisabitoddconsid-
ering that you can use the variable flavor without the slice to get the
sameresult!
Sliceswithnegativeindicesareuseful,though,forgettingthelastfew
charactersinastring. Forexample,flavor[-3:] is"pie".
Strings Are Immutable
To wrap this section up, let’s discuss an important property of string
objects. Strings are immutable, which means that you can’t change
themonceyou’vecreatedthem. Forinstance,seewhathappenswhen
youtrytoassignanewlettertooneparticularcharacterofastring:
>>> word = "goal"
>>> word[0] = "f"
Traceback (most recent call last):
File
"<pyshell#16>", line 1, in <module>
word[0] = "f"
TypeError: 'str' object does not support item assignment
77
4.2. Concatenation, Indexing, and Slicing
PythonthrowsaTypeError and tells you that str objectsdon’tsupport
itemassignment.
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
letteroftheword"goal":
>>> word = "goal"
>>> word = "f" + word[1:]
>>> word
'foal'
First, you assign the string "goal" to the variable word. Then you con-
catenatethesliceword[1:],whichisthestring"oal",withtheletter"f"
to get the string "foal". If you’re getting a different result here, then
makesureyou’reincludingthecoloncharacter(:) aspartofthestring
slice.
Review Exercises
You can nd the solutions to these exercises and many other bonus
resources online at
realpython.com/python-basics/resources
1. Createastringandprintitslengthusinglen().
2. Create two strings, concatenate them, and print the resulting
string.
3. Createtwostrings,useconcatenationtoaddaspacebetweenthem,
andprinttheresult.
4. Printthestring"zing" byusingslicenotationtospecifythecorrect
rangeofcharactersinthestring"bazinga".
78
4.3. Manipulate Strings With Methods
4.3 Manipulate Strings With Methods
Stringscomebundledwithspecialfunctions called string methods
that you can use to work with and manipulate strings. There are nu-
merousstringmethods available,butwe’llfocuson someofthemost
commonlyusedones.
Inthissection,you’lllearnhowto:
Convertastringtouppercaseorlowercase
Removewhitespacefromastring
Determineifastringbeginsorendswithcertaincharacters
Let’sgo!
Converting String Case
Toconvertastringtoalllowercaseletters,youusethestring’s.lower()
method. This is done by tacking .lower() onto the end of the string
itself:
>>> "Jean-Luc Picard".lower()
'jean-luc picard'
The dot (.) tells Python that what follows is the name of a method—
thelower() methodinthiscase.
Note
We’ll refer to string methods with a dot (.) at the beginning of
theirnames. Forexample,.lower() iswrittenwithaleadingdot
insteadofaslower().
This makes it easier to differentiate functions that are string
methodsfrombuilt-infunctionslikeprint() andtype().
79
4.3. Manipulate Strings With Methods
String methods don’t just work on string literals. You can also use
.lower() onastringassignedtoavariable:
>>> name = "Jean-Luc Picard"
>>> name.lower()
'jean-luc picard'
Theoppositeof.lower() is.upper(),whichconvertseverycharacterin
astringtouppercase:
>>> 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
thesefunctions,theimportantdistinctionhereishowthey’reused.
len() isastand-alonefunction. Ifyouwanttodeterminethelengthof
thename string,thenyoucallthelen() functiondirectly:
>>> len(name)
15
Onthe otherhand,.upper() and.lower() mustbeusedinconjunction
withastring. Theydonotexistindependently.
Removing Whitespace From a String
Whitespace is any character that is printed as blank space. This in-
cludesthingslikespacesandline feeds,whicharespecialcharacters
thatmoveoutputtoanewline.
Sometimesyouneedtoremovewhitespacefromthebeginningorend
of a string. This is especially useful when working with strings that
comefromuserinput,whichmayincludeextrawhitespacecharacters
byaccident.
80
4.3. Manipulate Strings With Methods
Therearethreestringmethodsthatyoucanusetoremovewhitespace
fromastring:
1. .rstrip()
2. .lstrip()
3. .strip()
.rstrip() removeswhitespacefromtherightsideofastring:
>>> name = "Jean-Luc Picard "
>>> name
'Jean-Luc Picard '
>>> name.rstrip()
'Jean-Luc Picard'
Inthisexample,thestring"Jean-Luc Picard " hasfivetrailingspaces.
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
longerhasthespacesattheend.
.lstrip() works just like .rstrip(), except that it removes whitespace
fromtheleft-handsideofthestring:
>>> name = " Jean-Luc Picard"
>>> name
' Jean-Luc Picard'
>>> name.lstrip()
'Jean-Luc Picard'
To remove whitespace from both the left and the right sides of the
stringatthesametime,use.strip():
>>> name = " Jean-Luc Picard "
>>> name
' Jean-Luc Picard '
>>> name.strip()
'Jean-Luc Picard'
81
4.3. Manipulate Strings With Methods
It’s important to note that none of .rstrip(), .lstrip(), or .strip() re-
moveswhitespacefrom the middle of the string. In each ofthe previ-
ousexamples,the spacebetween"Jean-Luc" and"Picard" ispreserved.
Determine If a String Starts or Ends With a
Particular String
Whenyouworkwithtext,sometimesyouneedtodetermineifagiven
string starts with or ends with certain characters. You can use two
stringmethodstosolvethisproblem: .startswith() and.endswith().
Let’slookatanexample. Considerthestring"Enterprise". Here’show
you use .startswith() to determine if the string starts with the letters
e andn:
>>> starship = "Enterprise"
>>> starship.startswith("en")
False
You tell .startswith() which characters to search for by providing a
string containing those characters. So, to determine if "Enterprise"
startswith the letters e and n, you call .startswith("en"). This returns
False. Whydoyouthinkthatis?
If you guessed that .startswith("en") returns False because "En-
terprise" starts with a capital E, then you’re absolutely right! The
.startswith() method is case sensitive. To get .startswith() to
returnTrue,youneedtoprovideitwiththestring"En":
>>> starship.startswith("En")
True
Youcanuse.endswith() todetermineifastringendswithcertainchar-
acters:
>>> starship.endswith("rise")
True
82
4.3. Manipulate Strings With Methods
Justlike.startswith(),the.endswith() methodiscasesensitive:
>>> starship.endswith("risE")
False
Note
TheTrue andFalse valuesarenotstrings. Theyareaspecialkind
of data type called a Boolean value. You’ll learn more about
Booleanvaluesinchapter8.
String Methods and Immutability
Recall from the previous section that strings are immutable—they
can’t be changed once they’ve been created. Most string methods
thataltera string, like .upper() and .lower(),actually return copies of
theoriginalstringwiththeappropriatemodifications.
Ifyouaren’tcareful,thiscanintroducesubtlebugsintoyourprogram.
TrythisoutinIDLE’sinteractivewindow:
>>> name = "Picard"
>>> name.upper()
'PICARD'
>>> name
'Picard'
When you call name.upper(), nothing about name actually changes. If
youneedtokeeptheresult,thenyouneedtoassignittoavariable:
>>> name = "Picard"
>>> name = name.upper()
>>> name
'PICARD'
name.upper() returns a new string "PICARD", which is reassigned to the
name variable. Thisoverrides theoriginalstring"Picard" thatyoufirst
assignedtoname.
83
4.3. Manipulate Strings With Methods
Use IDLE to Discover Additional String Methods
Strings have lots of methods associated with them, and the methods
introduced in this section barely scratch the surface. IDLE can help
you find new string methods. To see how, first assign a string literal
toavariableintheinteractivewindow:
>>> starship = "Enterprise"
Next, type starship followed by a period, but do not hit
Enter
. You
shouldseethefollowingintheinteractivewindow:
>>> starship.
Now wait for a couple of seconds. IDLE displays a list of every string
method,whichyoucanscrollthroughusingthearrowkeys.
A related shortcut in IDLE is the ability to use
Tab
to automatically
fill in text without having to type long names. For instance, if you
typeonlystarship.u andhit
Tab
,thenIDLEautomaticallyfillsinstar-
ship.upper because only one method that begins with a u belongs to
starship.
Thisevenworkswithvariable names. Try typing just the firstfewlet-
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 foryou.
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 converts the following strings to lowercase:
"Animals", "Badger", "Honey Bee", "Honey Badger". Print each lower-
casestringonaseparateline.
2. Repeat exercise 1, but convert each string to uppercase instead of
lowercase.
84
4.4. Interact With User Input
3. Write a program that removes whitespace from the following
strings,thenprintoutthestringswiththewhitespaceremoved:
string1 = " Filet Mignon"
string2 = "Brisket "
string3 = " Cheeseburger "
4. Write a program that prints out the result of .startswith("be") on
eachofthefollowingstrings:
string1 = "Becomes"
string2 = "becomes"
string3 = "BEAR"
string4 = " bEautiful"
5. Usingthe same four strings from exercise4,write a program that
uses string methods to alter each string so that .startswith("be")
returnsTrue forallofthem.
4.4 Interact With User Input
Now that you’ve seen how to work with string methods, let’s make
thingsinteractive!
In this section, you’ll learn how to get some input from a user with
input(). You’llwriteaprogramthatasksausertoinputsometextand
thendisplaysthattextbacktotheminuppercase.
EnterthefollowingintoIDLE’sinteractivewindow:
>>> 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
foryoutoentersomething!
85
4.4. Interact With User Input
Goaheadandtypesometextandpress
Enter
:
>>> input()
Hello there!
'Hello there!'
>>>
The text you entered is repeated on a new line with single quotes.
That’sbecauseinput() returnsasastringanytextenteredbytheuser.
Tomakeinput() abitmoreuser-friendly,youcangiveitaprompt to
display to the user. The prompt is just a string that you put between
the parentheses of input(). It can be anything you want: a word, a
symbol,aphrase—anythingthatisavalidPythonstring.
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:
prompt = "Hey, what's up? "
user_input = input(prompt)
print("You said: " + user_input)
Press
F5
toruntheprogram. ThetextHey, what's up? displaysinthe
interactivewindowwithablinkingcursor.
Thesinglespaceattheendofthestring"Hey, what's up? " makessure
thatwhentheuserstartstotype,thetextisseparatedfromtheprompt
withaspace. Whentheusertypesaresponseandpresses
Enter
,their
responseisassignedtotheuser_input variable.
86
4.4. Interact With User Input
Here’sasamplerunoftheprogram:
Hey, what's up? Mind your own business.
You said: Mind your own business.
Once you have input from a user, you can do something with it. For
example,thefollowingprogramtakesuserinput,convertsittoupper-
casewith.upper(),andprintstheresult:
response = input("What should I shout? ")
shouted_response = response.upper()
print(
"Well, if you insist..." + shouted_response)
Try typing this program into IDLE’s editor window and running it.
Whatelsecanyouthinkoftodowiththeinput?
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
inputback.
2. Write a program that takes input from the user and displays the
inputinlowercase.
3. Write a program that takes input from the user and displays the
numberofcharactersintheinput.
87
4.5. Challenge: Pick Apart Your User’s Input
4.5 Challenge: Pick Apart Your User’s
Input
Write a program named first_letter.py that prompts the user for in-
putwiththestring"Tell me your password:". Theprogramshouldthen
determine the first letter of the user’s input, convert that letter to up-
percase,anddisplayitback.
Forexample,iftheuserinputis"no",thentheprogramshoulddisplay
thefollowingoutput:
The first letter you entered was: N
Fornow,it’sokayifyourprogramcrasheswhen theuserentersnoth-
ingasinput—thatis, when theyjusthit
Enter
insteadoftypingsome-
thing. You’ll learn a couple of ways to deal with this situation in an
upcomingchapter.
You can nd the solutions to this code challenge and many other bonus
resources online at
realpython.com/python-basics/resources
4.6 Working With Strings and Numbers
When you get user input using input(), the result is always a string.
Therearemanyothersituations in which input is given to a program
asa string. Sometimesthosestringscontainnumbersthatneedtobe
fedintocalculations.
Inthissection,you’lllearnhowtodealwithstringsofnumbers. You’ll
seehowarithmeticoperationsworkonstringsandhowtheyoftenlead
tosurprisingresults. You’llalsolearnhowtoconvertbetweenstrings
andnumbertypes.
Using Strings With Arithmetic Operators
You’ve seen that string objects can hold many types of characters, in-
cluding numbers. However, don’t confuse numerals in a string with
88
4.6. Working With Strings and Numbers
actual numbers. For instance, try this bit of code out in IDLE’s inter-
activewindow:
>>> num = "2"
>>> num + num
'22'
The + operator concatenates two strings together, which is why the
resultof "2" + "2" is "22" andnot"4".
You can multiply strings by a number as long as that number is an
integerorwholenumber. Typethefollowingintothe interactive win-
dow:
>>> num = "12"
>>> num * 3
'121212'
num * 3 concatenatesthreeinstancesofthestring"12" andreturnsthe
string"121212".
Compare this operation to arithmetic with numbers. When you mul-
tiplythenumber12bythe number3,theresultisthesameasadding
three12stogether. The same is true for a string. Thatis,"12" * 3 can
be interpreted as "12" + "12" + "12". In general, multiplying a string
byanintegern concatenatesn copiesofthatstring.
Youcanmovethenumberontheright-handsideoftheexpressionnum
* 3 totheleft,andtheresultisunchanged:
>>> 3 * num
'121212'
What do you think happens if you use the * operator between two
strings?
89
4.6. Working With Strings and Numbers
Type"12" * "3" intheinteractivewindowandpress
Enter
:
>>> "12" * "3"
Traceback (most recent call last):
File
"<stdin>", line 1, in <module>
TypeError: can't multiply sequence by non-int of type 'str'
Python raises a TypeError and tells you that you can’t multiply a se-
quencebyanon-integer.
Note
A sequence is any Python object that supports accessing ele-
mentsbyindex. Stringsaresequences. You’lllearnaboutother
sequencetypesinchapter9.
When you use the * operator with a string, Python always expects an
integerontheothersideoftheoperator.
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
PythonthrowsaTypeError becauseitexpectstheobjectsonbothsides
ofthe+ operatortobeofthesametype.
Ifanobjectoneithersideof + isastring,thenPythontriestoperform
stringconcatenation. Itwillonly perform additionifbothobjectsare
numbers. So,toadd"3" + 3 andget6,youmustfirstconvertthestring
"3" toanumber.
90
4.6. Working With Strings and Numbers
Converting Strings to Numbers
The TypeError examples in the previous section highlight a common
problem when applying user input to an operation that requires a
numberandnotastring: typemismatches.
Let’slookatanexample. Saveandrunthefollowingprogram:
num = input("Enter a number to be doubled: ")
doubled_num
= num * 2
print(doubled_num)
Ifyouenteredthenumber2 attheprompt,thenyouwouldexpectthe
outputto be 4. But in this case, youwould get 22. Remember, input()
alwaysreturnsastring,soifyouinput2,thennum isassignedthestring
"2", not the integer 2. Therefore, the expression num * 2 returns the
string"2" concatenatedwithitself,whichis"22".
To perform arithmetic on numbers contained in a string, you must
firstconvertthem fromastringtype toanumbertype. Therearetwo
functionsthatyoucanusetodothis: int() andfloat().
int() stands for integer and converts objects into whole numbers,
whereasfloat() standsforoating-point number andconvertsob-
jects into numbers with decimal points. Here’s what using each one
lookslikeintheinteractivewindow:
>>> int("12")
12
>>> float("12")
12.0
Notice how float() adds a decimal point to the number. Floating-
pointnumbersalwayshaveatleastonedecimalplaceofprecision. For
this reason, you can’t change a string that looks like a floating-point
number into an integer because you would lose everything after the
decimalpoint.
91
4.6. Working With Strings and Numbers
Tryconvertingthestring"12.0" toaninteger:
>>> int("12.0")
Traceback (most recent call last):
File
"<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: '12.0'
Eventhoughtheextra0 afterthe decimalplacedoesn’taddanyvalue
to the number, Python won’t change 12.0 into 12 because it would re-
sultinalossofprecision.
Let’s revisit the program from the beginning of this section and see
howtofixit. Here’sthecodeagain:
num = input("Enter a number to be doubled: ")
doubled_num = num * 2
print(doubled_num)
The issue is on the line doubled_num = num * 2 because num is a string
and2 isaninteger.
Youcanfixtheproblembypassingnum toeitherint() orfloat(). Since
the prompts asks the user to input a number, and not specifically an
integer,let’sconvertnum toafloating-pointnumber:
num = input("Enter a number to be doubled: ")
doubled_num = float(num) * 2
print(doubled_num)
Nowwhen you run this program andinput 2, you get 4.0 as expected.
Tryitout!
Converting Numbers to Strings
Sometimes you need to convert a number to a string. You might do
this, for example, if you need to build a string from some preexisting
variablesthatareassignedtonumericvalues.
92
4.6. Working With Strings and Numbers
As you’ve already seen, concatenating a number with a string pro-
ducesaTypeError:
>>> 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
Since num_pancakes is a number, Python can’t concatenate it with the
string "I'm going to eat". To build the string, you need to convert
num_pancakes toastringusingstr():
>>> num_pancakes = 10
>>> "I am going to eat " + str(num_pancakes) + " pancakes."
'I am going to eat 10 pancakes.'
Youcanalsocallstr() onanumberliteral:
>>> "I am going to eat " + str(10) + " pancakes."
'I am going to eat 10 pancakes.'
str() canevenhandlearithmeticexpressions:
>>> total_pancakes = 10
>>> pancakes_eaten = 5
>>> "Only " + str(total_pancakes - pancakes_eaten) + " pancakes left."
'Only 5 pancakes left.'
Inthenextsection,you’lllearnhowtoformatstringsneatlytodisplay
valuesinanice,readablemanner. Beforeyoumoveon,though,check
yourunderstandingwiththefollowingreviewexercises.
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
1. Createastringcontaininganinteger,thenconvertthatstringinto
an actual integer object using int(). Test that your new object is
anumberbymultiplyingitby anothernumberanddisplayingthe
result.
2. Repeatthepreviousexercise,butuseafloating-pointnumberand
float().
3. Createastringobjectandanintegerobject,thendisplaythemside
bysidewithasingleprintstatementusingstr().
4. Write a program that uses input() twice to get two numbers from
theuser,multipliesthenumbers together, and displaystheresult.
If the user enters 2 and 4, then your program should print the
followingtext:
The product of 2 and 4 is 8.0.
4.7 Streamline Your Print Statements
Suppose you have a string, name = "Zaphod", and two integers, heads
= 2 and arms = 3. You want to display them in the string "Zaphod has
2 heads and 3 arms". This is called string interpolation, which is
justa fancy way of saying that you want to insert some variables into
specificlocationsinastring.
Onewaytodothisiswithstringconcatenation:
>>> 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
knownasf-strings.
Theeasiestwaytounderstandf-stringsistoseetheminaction. Here’s
whattheabovestringlookslikewhenwrittenasanf-string:
>>> f"{name} has {heads} heads and {arms} arms"
'Zaphod has 2 heads and 3 arms'
Therearetwoimportantthingstonoticeabouttheaboveexample:
1. The string literal starts with the letter f before the opening quota-
tionmark.
2. Variable names surrounded by curly braces ({}) are replaced by
theircorrespondingvalueswithoutusingstr().
YoucanalsoinsertPythonexpressionsbetweenthecurlybraces. The
expressionsarereplacedwiththeirresultinthestring:
>>> n = 3
>>> m = 4
>>> f"{n} times {m} is {n*m}"
'3 times 4 is 12'
It’s a good idea to keep any expressions used in an f-string as simple
aspossible. Packing abunchofcomplicatedexpressionsintoastring
literal can result in code that is difficult to read and difficult to main-
tain.
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.
ReturningtotheZaphodexample,youcanuse.format() toformatthe
stringlikethis:
>>> "{} has {} heads and {} arms".format(name, heads, arms)
'Zaphod has 2 heads and 3 arms'
f-strings are shorter and sometimes more readable than using .for-
mat(). You’llseef-stringsusedthroughoutthisbook.
95
4.8. Find a String in a String
Foranin-depthguidetof-stringsandcomparisonstootherstringfor-
mattingtechniques,checkoutReal Python’s
“Python3’sf-Strings: An
ImprovedStringFormattingSyntax(Guide).”
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
astringobject named animal withthevalue"newt". Then usethese
objects to print the following string using only string concatena-
tion:
0.2 kg is the weight of the newt.
2. Displaythesamestringbyusing.format() andempty{} placehold-
ers.
3. Displaythesamestringusinganf-string.
4.8 Find a String in a String
Oneofthemostusefulstringmethodsis .find(). Asitsnameimplies,
this method allows you to find the location of one string in another
string—commonlyreferredtoasasubstring.
To use .find(), tack it to the end of a variable or a string literal with
thestringyouwanttofindtypedbetweentheparentheses:
>>> phrase = "the surprise is in here somewhere"
>>> phrase.find("surprise")
4
Thevaluethat.find() returnsistheindexofthefirstoccurrenceofthe
stringyoupasstoit. Inthiscase,"surprise" startsatthefifthcharacter
of the string "the surprise is in here somewhere", which has index 4
becausecountingstartsatzero.
96
This is a sample from “Python Basics: A Practical
Introduction to Python 3”
WiththefullversionofthebookyougetacompletePythoncurriculum
togoallthewayfrombeginnertointermediate-level. Everystepalong
thewayisexplainedandillustratedwithshort&clearcodesamples.
Codingexerciseswithineachchapterandourinteractivequizzeshelp
fast-trackyourprogressandensureyoualwaysknowwhattofocuson
next.
Become a fluent Pythonista and gain programming knowledge you
canapplyinthereal-world,today:
If you enjoyed the sample chapters you can purchase a full
version of the book at
realpython.com/pybasics-book