Escolar Documentos
Profissional Documentos
Cultura Documentos
1SIMPLEPROGRAMS
4
1.1THEORY:IntroductiontoPython 4
1.1.1WhatisPython?
4
1.1.2Pythonindatascience 4
1.1.3AshorthistoryofPython
5
1.1.4Firstprogramexample 5
1.1.5Practice 5
1.1.5.1Mainapplications
5
1.1.5.2OlderversionofPython 5
1.1.5.3Hello,Python 5
1.1.5.4VersionsofPython
6
1.1.5.5Guesstheresult 6
1.1.5.6Theoriginofthename
6
1.1.5.7DatasciencetoolsinPython 6
1.2THEORY:Overviewofthebasicprogram 7
1.2.1TheHelloWorldprogram
7
1.2.2Shortexplanation 7
1.2.3Printingquotes
7
1.2.4Possibleerrors 8
1.2.5Summary 8
1.2.6Practice
8
1.2.6.1Whatisprint 8
1.2.6.2Plainmessage
8
1.2.6.3AliceinWonderland 8
1.2.6.4Printatext 8
1.2.6.5Yourname
8
1.2.6.6Multiplequotes 9
1.3THEORY:Multi-lineprograms
9
1.3.1Practice 10
1.3.1.1Counttheempty 10
1.4THEORY:Programexecution 0
1
1.4.1Interpretation 10
1.4.2Interpretedorcompiled? 1
1
1.4.3PythonVirtualMachine 11
1.4.4Summary 12
1.4.5Practice 2
1
1.4.5.1Howithappens 12
1.4.5.2Coderepresentations 2
1
1.4.5.3VirtualMachine 12
1.4.5.4Interpreter 12
1.4.5.5Chooseaction 2
1
1.4.5.6LifecycleofaPythonprogram 12
1.4.5.7Defaultinterpreter 12
1
1.4.5.8Documentation 13
1.4.5.9Whatsteptochoose? 3
1
1.4.5.10Bytecode 3
1
1.4.5.11PythonVirtualMachine 13
1.5THEORY:Takinginput 13
1.5.1Readinginputfromauser 3
1
1.5.2Clearmessages 14
1.5.3Importantdetails 4
1
1.5.4Conclusion 14
1.5.5Practice 14
1.5.5.1Userinput 4
1
1.5.5.2Asaninteger 14
1.5.5.3Theendofaninput 5
1
1.5.5.4Input()function 15
1.5.5.5Whattoexpect? 15
1.5.5.6Sum 5
1
1.5.5.7Trickyquestion 15
1.5.5.8Sumoftwofloats 5
1
1.5.5.9Datatype 16
1.5.5.10Test 16
1.5.5.11Waystoread 6
1
1.5.5.12Difference 16
1.5.5.13Catchysong 16
1.6THEORY:Programwithnumbers 7
1
1.6.1Readingnumbersfromuserinput 17
1.6.2Freeairmiles 7
1
1.6.3Advancedformsofassignment 18
1.6.4Countervariable 8
1
1.6.5Conclusion 19
1.6.6Practice 19
1.6.6.1Badomen 9
1
1.6.6.2Undercover 19
1.6.6.3Whenyou'llhaveafreetrip? 9
1
1.6.6.4Calculatinganexpression 20
1.6.6.5Thelastdigitofanumber 20
1.6.6.6CalculatingSVP 1
2
1.6.6.7Dividenutsequallybetweensquirrels 21
1.6.6.8Thefirstdigitofatwo-digitnumber 22
1.6.6.9Differenceoftimes 2
2
1.6.6.10Thesumofdigits 23
1.6.6.11Pumpkinpie 4
2
1.6.6.12Savingsaccount 24
1.6.6.13Goodrestonvacation 24
1.6.6.14Desks 5
2
1.7THEORY:Commandlinearguments 25
1.7.1Runningfromthecommandline 25
2
1.7.2Systemmodule 6
2
1.7.3Checkingtheinput 26
1.7.4WithintheIDE 6
2
1.7.5Summary 27
1.7.6Practice 27
1.7.6.1Length 7
2
1.8THEORY:Argparsemodule 27
1.8.1Gettingstartedwithargparse 8
2
1.8.2Addingarguments 28
1.8.3Parsingarguments 29
1.8.4Howdoyouactuallyusethatinthecommandline? 0
3
1.8.5Summary 32
1.8.6Practice 2
3
1.8.6.1Argumentsasflags 32
2MODULEANDPACKAGES 2
3
2.1THEORY:Loadmodule 32
2.1.1Modulebasics 2
3
2.1.2Moduleloading 33
2.1.3Built-inmodules 4
3
2.1.4Summary 34
3BUILD-iNS 5
3
3.1THEORY:Anyandall 35
3.1.1Functionany() 6
3
3.1.2Functionall() 36
3.1.3Non-booleanvalues 7
3
3.1.4Conditions 37
3.1.5Summary 38
3.1.6Practice 8
3
3.1.6.1Objects 38
3
1S
IMPLEP
ROGRAMS
1.1THEORY:IntroductiontoPython
1.1.1WhatisPython?
Python is a modern general-purpose programming language initially developed by a Dutch programmer
named Guido van
Rossum in the late 1980s. The name comes from the popular Monty Python show, not the
snake, as
you might think.
This language has a clean,
uniform, and
well-readable syntax and is designed to
beeasytolearnanduseinpractice.
Nowadays, Python is one of
the most
popular programming languages worldwide, according to
the
TIOBE
index.
The number of programmers who use it is growing every day! The language has a huge community of
developers around the world.
If
you
have a problem, you can always ask other programmers for help or find
asuitableansweronasitelikeS tackOverflow.D evelopingsoftwarewithPythoniseasyandfun!
Pythonhasawiderangeofpossibleapplications,especiallyin:
● Webdevelopment;
● Datascience(includingmachinelearning);
● Scripting(taskautomation,suchastextprocessingorsimulationoftypicaluseractions).
Itisalsousedindesktopdevelopment,thoughlesscommonly.
1.1.2Pythonindatascience
Python's huge
popularity in
recent
years
is
mostly due
to
its
use
in
data science. What makes it better than
otherlanguagesforthispurpose?Well,there'reanumberofreasons:
● Its simple syntax allows people from non-programming backgrounds to use it for data processing
andmodeltrainingwithoutspendingmuchtimelearninganewlanguage.
● Python supports a very large number of
third-party libraries for
machine learning,
neural networks,
statistics,andnumericcalculations,whichmakesyourjobmucheasier.
● With Python, it
is
possible to
collect, clean, and
explore data, as well
as
train
models
and visualize
theresults—allinonesetting!
● PythonMLdevelopers'communityisverylarge,soyoucanalwaysfindsupportforyourtasks.
Asyoucansee,Pythondoeshavealottoofferfordatascienceenthusiasts.
1.1.3AshorthistoryofPython
Like other programming languages, Python has gone through a number of versions. Python 1.0 was
releasedin1994andlaidthebasicprinciplesofthelanguagewithemphasisonsimplicity.
Python 2.0
was
released in
2000. This
version has become very popular among programmers. Different 2.x
subversions (2.6, 2.7) are still used in various projects and libraries. The symbol x in 2.x means any
subversionofPython2.
Python 3.0 was the next major version released in 2008. It broke backward compatibility with its
predecessorsinordertoridthelanguageofhistoricclutterandmakePythonmorereadableandconsistent.
Today,twosimilarbutincompatibleversionsofPythonarecommonlyused.
Throughoutthiscourse,wewillbeworkingwithPython3.x.
4
1.1.4Firstprogramexample
HereisasinglelineofPythoncodethatprints
Learn
Python
to
be
great!.
print ("Learn Python to be
great!" )
For
now, you
do
not need
to
understand how this
code works: just
appreciate its
beautiful syntax that isn't
toofarfromnormalEnglish.
Knowing about the compatibility of
Python versions will
likely help you in
the
future. If you know it, you can
easily read through the older code and correct it, so it will run without any mistakes in newer Python
versions.
When did Python become incompatible with its
earlier
versions? Enter the number of the version that broke
backwardcompatibility.Youdon'tneedtousetheprintstatementorquotationmarks,justwritethenumber.
1.1.5Practice
Computerscience>Programminglanguages>Python> Basics>Simpleprograms>IntroductiontoPython
1.1.5.1M
aina
pplications
As a general-purpose language, Python has many applications. Select all options which represent main
applicationsforPython.Selectoneormoreoptionsfromthelist
taskautomation (X)
webdevelopment (X)
machinelearning (X)
1.1.5.2O
lderv
ersiono
fP
ython
Nowadays, different
subversions
of
Python 3 are
used
in
projects and
libraries, and
there are
new versions
under development. However, what about Python 2? Are its subversions still used? Choose one correct
option.S electoneoptionfromthelist:
Python2isnotusedatallnow
SomeprojectsusePython3,whileothersarestillwritteninPython2 (X)
Python2isstillmorepopularthanPython3
Python2ismoreconvenientfordatascienceandusedparticularlyforthispurpose
1.1.5.3H ello,P ython
Here is
a simple one-line Python program that prints a text. Copy it to the text area below and then click
the
Run button (or
Check button if you use an IDE). Our server will verify whether the program is correct
andwilltellyoutheresult.p rint( "Learn Python to be great!" )
Now,youdonotneedtounderstandhowtheprogramworks,justenjoyit!:)
1.1.5.4V ersionso fP ython
WhatversionofPythonisusedthroughoutthiscourse?Selectoneoptionfromthelist:
1.x
2.x
2.7
3.x (X)
1.1.5.5G
uesst
her
esult
In the topic, you
saw
a one-line
code snippet.
We
will
describe
it
in
detail
in
further
topics,
but
we
bet
you
are able to
write
your
first
program even now!
Look
at
the
code
examples below and guess
which
one
will
outputthephrase"Iamreadytolearn!".Selectoneoptionfromthelist:
write"Iamreadytolearn!"
output("Iamreadytolearn!")
enter"Iamreadytolearn!"
print("Iamreadytolearn!") (X)
5
1.1.5.6T
heo
rigino
ft
hen
ame
WhywastheprogramminglanguageyouaregoingtostudycalledPython?Selectoneoptionfromthelist:
Itwasnamedafterasnake.
Alltheanswersarecorrect!
Itwasnamedafterarevolver.
ItwasnamedaftertheMontyPythonshow. (X)
1.1.5.7D
atas
ciencet
oolsi
nP
ython
Recently,Pythonhasgainedpopularityintheareaofdatascience.Whydidithappen?Selectoneoptionfromthelist:
Pythonhasmanytoolsforcollectingandcleaningdata.
Pythonhasthird-partytoolsformachinelearningandneuralnetworks.
Python'ssimplesyntaxmakestheprocessofwritingcodefaster.
Pythonhastoolsfornumericcalculationsandstatistics.
YoucaneasilyvisualizeyourresultsusingPython.
Alloftheaboveoptionsarecorrect (X)
6
1.2THEORY:Overviewofthebasicprogram
In
this
topic,
you
will
learn
how to
develop
your
first Python programs. Despite the fact that these programs
arequitesimple,theyarestillsyntacticallycorrectandshowthatprogramminginPythonisatreat.
1.2.1TheHelloWorldprogram
Our
first
example
will
be
Hello,
World!
It
is
traditionally
used
to
introduce
beginners
to
a new
programming
language.
print
("
Hello,
World!"
)
As you can see, it consists of a single line
and
just
prints
a string passed
in
the parentheses, but
without
quotes. You may run this
code online (just copy
it
and
click on the triangle) or follow these installation tips.
Youshouldgetthisresult:
Hello,World!
Althoughthiscodeisverysimple,wewillgothroughitinsomemoredetail.
1.2.2Shortexplanation
Here, print is
the name of
a function. A function is
a block of code that does some useful work for you, e.g.
prints a text.
In
some sense, a function is a subprogram that can be reused within your programs. When the
nameofafunctionisfollowedbyparentheses,itmeansthatitwascalledtogettheresult.
Let's go further: "Hello, World!" is a Python string. All strings are surrounded by either single or double
quotes, so 'Hello, World!' is also a valid string. You may replace this string with another one, and the program
willprintthenewstring.Forexample:
print ('
Python 3.x' )
Asyoumightguess,thisprogramwillprint:
Python3.x
1.2.3Printingquotes
Now imagine that
the
string
you
want
to
print
already
contains some
type
of
quotation
mark.
If
you
would
liketoincludequotesintoastring,thenenclosethisstringinquotesofanothertype,e.g.:
print("Yes, I'm ready to learn Python.")
Part of the string with I'm is printed correctly, because you used double quotes "..." to enclose
the
whole
string:
Yes, I'm ready to learn Python.
If you write it in the following wrong way: print('Yes, I'm ready to learn Python.') your
program won't know where the string starts and ends.You can try to run all the examples using the link
providedearlier.ThiswillhelpyoufamiliarizeyourselfwithPython.
1.2.4Possibleerrors
Eventhissimplelineofcodemaycontainerrors,mostcommonofthemare:
● puttingextraindentation
print("Hello, World!")
Thisdoesnotworkbecauseofextraspacesbeforeprint.
● callingthefunctionbythewrongname
pint("Hello, World!")
Thislinecontainspintinsteadofprint.Makesuretorefertoeveryfunctionbyitspropername.
● writingnamesinthewrongcase
PRINT("All caps")
Again,Print,printandPRINTarenotthesame.Namesarecase-sensitiveinPython.
● missingoneorbothquotesforastring
print("Python)
Thisdoesnotworkbecauseofmissingclosingquotes.
● missingoneormoreparentheses
print("I have no end"
Becarefulwithparentheses,especiallywhencallingafunction.
Nowyoushouldn'thaveanyserioustroublewithsuchprograms.
7
1.2.5Summary
In
this
topic,
we've written our first program in Python, broke it down, printed some strings, and looked at the
mostcommonerrorsyoumayencounterattheverystart.
1.2.6Practice
Computerscience>Programminglanguages>Python> Basics>Simpleprograms>Overviewofthebasicprogram
1.2.6.1W
hati
sp
rint
WhatisprintinPython3?Selectoneoptionfromthelist
afunction (X)
acommand
anexpression
astatement
1.2.6.2P
lainm
essage
WriteaprogramthatprintsoutastringWelovePython!Solution:p
rint
("
We
love
Python!"
)
1.2.6.3A
licei
nW
onderland
ThetitleofAlice'sAdventuresinWonderlandisoftenshortenedtoAliceinWonderland.
Now, when we know
how
to
print
strings with quotes, we won't shorten the title. Please print the full version
ofthebook'stitle.Solution:p
rint ("Alice's Adventures inWonderland" )
1.2.6.4P
rinta
t
ext
SelectallcorrectwaystowriteasimpleprogramwhichprintsastringinPython.
a)p rint
("
Hello" )
(X)
b) p
rint("Hello" )
c)p rint(Hello)
d)p rint
('Hello' ) (X)
1.2.6.5Y
ourn
ame
Write a program that prints the
string
"My
name
is
" followed
by
your
name
like
in
the
output
example.
All
wordsinthisstringmustbeseparatedbyasinglespace.
Outputexample:M
y
name
is
John Solution:
print
("
My
name
is
Maria"
)
1.2.6.6M
ultipleq
uotes
Selectallthecorrectstringstoprint.
print("Theship'snameis'Brave'.") (X)
print('Cat'spaws.')
print('Theword"Ciao"means"hello"inItalian.') (X)
print("And"Ciao"isItalian"Bye".")
8
1.3THEORY:Multi-lineprograms
We hope you
have already learned how
to
write simple Python programs consisting of a single line that just
prints a text. However, real programs contain a significant number of lines: from tens and hundreds for
small scripts to
thousands and even more for
large projects.
So,
in this lesson, you will write programs that
print multiple lines. Let's consider an example, the following code prints exactly three strings, each on a new
line:
print("I")
print("know")
print("Python")
Theoutputis:
I
know
Python
YoucanrunthisexamplehereorlocallyifyouhavealreadyinstalledPythononyourcomputer.
There are other ways to
print
the
same text using just
one
function call.
We
will
consider them in
the
next
topics.Thep rint functionalsoallowsyoutoprintanemptylinewithnostringspecified:
print("I")
print()
print("know")
print()
print("Python")
Here'stheoutput:
I
know
Python
However,skippingthelinewillhavenoeffect:
print("And")
print("you?")
Theoutputis:
And
you?
Nowit'stimetosolvesomeproblems.
1.3.1Practice
Computerscience>Programminglanguages>Python>B
asics>Simpleprograms>Multi-lineprograms
1.3.1.1C
ountt
hee
mpty
Howmanyemptylineswillthiscodeprint?Theexpectedanswerisanumber.
print("hello")
print("")
print()
print("bye") 2
Answer:
9
1.4THEORY:Programexecution
What does it mean to write a program in Python? From the programmer's point of
view,
it
implies writing
certain instructions in a file and then executing it in Python. We can simply create a .txt file with the
followingstatement:
print("Hello, World!")
Andthenexecuteitfromthecommandlineinthefollowingway(suppose,wenamedit%example.txt%):
pythonexample.txt
You may know that all
Python
files
are
supposed to have a .py extension, but we can write the code in a .txt
file as well. Usually, programmers don't use text editors for programming, they use IDEs (Integrated
Development Environment), a special program designed for software development. However, one thing
remains—thesourcecodeisjustasetofspecificinstructions.
It's not all that simple. You may have heard that there are interpreted and compiled programming
languages. Maybe you've also heard that Python is an interpreted language. But do you know what that
means?
1.4.1Interpretation
Theprocessofprogramexecutionmayseemsomethinglikethistoyou:
Writingascript →
Somemagic →
Everythingworks!
Theinterpretationp
art,infact,fitsintothemiddlepartofthisscheme:
Writingascript →
Interpretation →
Everythingworks!
The
majority of
Python
programmers just
stop inquiring further from
this point. Let's try to explain what the
interpretationmeansinthiscase.
During the
interpretation part, the
software goes through your
program and
executes the code,
line
by
line.
This software is called an interpreter. It is a part of the standard Python installation package. So, an
interpreterisalayerofsoftwarelogicbetweenyoursourcecodeandyourhardware.
An interpreter
can
be
written
in
any
programming language. The default Python interpreter is written in C,
itiscalledCPython.ThisiswhatweinstallfromtheofficialPythonwebsite.
1.4.2Interpretedorcompiled?
To understand what is under the hood
of
Python,
let's
find
out
what lies
behind the
concept of
interpreted
andcompiledlanguages.
With compiled languages, when a programmer wants to run a source code, they need to use a compiler first.
It
is
the special software that translates the source code into a special language. This language is called the
machine code. It is
a set
of
instructions executed directly
by
your
processor. The problem is
that different
types of computers operate with different machine codes, so the source code
compiled in Windows may
notworkonaMac.
Interpreted languages also include a compilation step, but the compiler turns your source code into the
so-called byte code, an intermediate language. The byte code is a lower level (more detailed),
10
platform-independent, and
more
efficient
version
of
the
source
code.
We
need a special abstract computer
(thePythonVirtualMachineinourcase,butmoreonthatlater!)toexecutethiscode.
Infact,theinterpretationstepconsistsofthreephases:
Byte code is saved as a .pyc file after the compilation. If the source code of the program has not been
changedsincethelastcompilation,Pythonwillloadtheexisting.pycfile,bypassingthecompilationstep.
Below you can see the readable byte code. The second column contains the instructions in the order of their
execution. If something is unclear, it's OK. You don't have to know the byte code inside out to write
programs.
1 0L
OAD_NAME 0(
print)
2L
OAD_CONST 0(
'Hello,World!')
4C
ALL_FUNCTION
1
6R
ETURN_VALUE
1.4.3PythonVirtualMachine
The byte code is supplied to the PVM (Python Virtual Machine) after the
compilation. It
may
sound quite
impressive, but in fact, it is nothing more than a big piece of code that iterates through the byte code
instructions, which were received from a compiler, and executes them one by one. It is an internal part of the
Pythonsystemandyoudon'tneedtoinstallitasaseparateprogram.
PVMinCPythondoesnotconvertthebytecodeintothemachinecode.Itcanexecuteitrightaway.
This complexity is hidden from a programmer for
a reason.
The
interpretation
is
fully automated, and you
won't need to think about
it
at
all.
Remember
that
Python programmers simply
write the code
and
run
the
files,Pythondoeseverythingelse.
1.4.4Summary
Python is an interpreted language. It compiles the source code to the byte code before the execution.
ExecutingaPythonprogramimpliesbothcompilationandinterpretation.
When
your program is
turned
into
the
byte code,
it's
executed line
by
line
by
the PVM. That's why Python is
slowerthancompiledlanguagessuchasC++orC.
1.4.5Practice
Computerscience>Programminglanguages>Python> Basics>Simpleprograms>Programexecution
1.4.5.1H
owi
th
appens
Below
is
a description of
a Python
interpretation process, divided into smaller steps. Sort these steps in the
correct order (from 'you write code' to
'everything
works!'),
so
that
they
would explain
together what
really
happensduringPythoninterpretation.
1. Youwritecode.
2. Thecompilerturnsyoursourcecodeintobytecode.
3. ThecodegoestoPythonVirtualMachine.
4. VirtualMachineexecutescodeinstructionsonebyone.
5. Everythingworks!
11
1.4.5.2C
oder
epresentations
Sort these different code representations from most human-readable and high-level to most
computer-readableandlow-level.
1. Sourcecode
2. Bytecode
3. Binarymachinecode
1.4.5.3V
irtualM
achine
WhatisaPythonvirtualmachine?Selectoneoptionfromthelist:
AprogramwhichconvertsPythonsourcecodeintobytecode.
AnimplementationofPythonforthe.NETframework.
ApieceofcodeemulatingPython,whichreadsandexecutesbyte-codeinstructions. (X)
1.4.5.4I
nterpreter
Whatisaprogramminglanguageinterpreter?Selectoneoptionfromthelist:
Aprogramwhichcompilesyoursourcecodeintobytecode.(No,thisisacompiler)
Aprogramwhichreadsandexecutescodelinebyline. (X)
Standardlibraryofaprogramminglanguage.
1.4.5.5C
hoosea
ction
Whichoftheseisdonebyaprogrammer?Selectoneoptionfromthelist:
Codecompilation
Codeexecution
Runningthescript (X)
Interpretationofcode
1.4.5.6L
ifecycleo
fa
P
ythonp
rogram
OrderstagesinthelifecycleofaPythonprogramfrombeginningtoend.
1. Writingsourcecode
2. Runningsourcecode
3. Compilation
4. Executionofbytecode
1.4.5.7D
efaulti
nterpreter
ThedefaultinterpreterforPythoniscalledCPython.Inwhichlanguageisitwritten? Answer: C
1.4.5.8D
ocumentation
One of the most important skills for programmers is to know
where
to find the
information. And the
best
place to start looking for information about Python is the official documentation. Whenever you have
questionsaboutPython,trytochecktheofficialdocumentation.
Right now your
task is
to open the
official
website:
https://docs.python.org/3/. Head into "Tutorial", find the
followingsentence,andmatchthegapswiththecorrectwords.
Python's elegant syntax and ___[1]___,
together
with
its ___[2]___, make it an ideal language for scripting and
rapid___[3]___inmanyareasonmostplatforms.
1. dynamictyping
2. interpretednature
3. applicationdevelopment
Emportuguês: https://docs.python.org/pt-br/3/
1.4.5.9W
hats
tept
oc
hoose?
Imagine you
want
to
create a long
and
sophisticated code
that predicts your
future.
You wrote a script and
run
it.
What happens to
the
source code then?
How do we call the step when the source code is turned into
thebytecodetobeprocessedbythePythonVirtualMachine?
Interpretation
Compilation (X)
12
Writingacode
1.4.5.10B
ytec
ode
Selecttwocorrectstatementsaboutbytecode.Selectoneormoreoptionsfromthelist:
Bytecodeisahigherlevelversionofsourcecode.
Bytecodeisalowerlevelversionofsourcecode. (X)
Bytecodeisexecuteddirectlybyyourprocessor.
Bytecodeisdifferentondifferentplatforms.
Bytecodeisplatform-independent. (X)
1.4.5.11P
ythonV
irtualM
achine
PythonVirtualMachine… Selectoneormoreoptionsfromthelist:
...transformsthesourcecodeintothebytecode.
...isthelaststepofwhatiscalled"Pythoninterpreter". (X)
...mustberunbyaprogrammermanuallybeforerunningthecode.
...automaticallyexecutesthebytecodelinebyline. (X)
13
1.5THEORY:Takinginput
Sometimes programs need to interact with users, either to receive some data or to deliver some sort of
result.Andthat'swhenthe
input()functionstealstheshow.
1.5.1Readinginputfromauser
The input data we want to
get
is
nothing but
some value entered by the user. The input() function reads
thisvalueandreturnsitinaprogramasastring.Forexample,thefollowingprogramreadstheusernameandprintsagreeting.
user_name =input()
print('Hello, '+ user_name)
In the first line, the program will wait for the user to enter something as input, which we will
assign to
a
variable so we can use it later. In the second line, the program appends the entered name to the end of
'Hello, 's tringandprintsthewholephraseasaresult.IfauserentersS auron ,thisprogramprints:
Hello, Sauron
So,yourprogramprintsaresultthatdependsontheuser'sinput(name).
1.5.2Clearmessages
It is
highly
recommended to
state
clearly what
type
of
input we expect
from our
user.
To
do
so,
the
input()
functionmaytakeanoptionalargument,thatisamessage:
user_name =
input('Please, enter your name: ')
print('Hello, ' + user_name)
Theprogramstarts,theuserseesthemessage,enterstheirnameandgetstheresultasfollows:
Please, enter your name: Sauron
Hello, Sauron
Anotherwaytodothisistoprintthemessageseparately:
print('Enter your name: ')
user_name =
input()
print('Hello, ' + user_name)
There's no
big
difference
actually: in
the
previous example, the
input
will
be
printed in
the
same line
as the
message,whileinthiscaseitwillbewritteninthenextline.So,youmaychoosewhateveryoulike.
Although it is recommended to print messages for users, avoid them in our educational programming
challenges,otherwiseyourcodemaynotpassourtests.
1.5.3Importantdetails
Let's
dig
into some details. First
of
all,
how
long can the
user's input be? The second question is: how does
theprogramunderstandthatthepersonenteredeverythingtheywanted?
Here's a thing about the input() function: as soon as the program has started executing this function, it
stops and waits for the
user to
enter some value and press Enter.
That
also
means that
if
there's no
input
fromtheuser,theprogramwillnotexecuteanyfurther.
What else should you remember? Well, this: any value you enter, the function sees as a string. It
doesn't
matterifyouenterdigitsorletters,theinputwillbeconvertedtoastring.
Ifyouwantanumbertobeanumber,youshouldwriteitexplicitly:
print("What's your favorite number?")
value =
int(input()) # now value keeps aninteger number
However,becareful:inthesecircumstances,ifauserentersanon-integervalue,anE rror willappear.
Toreadseveralinputs,youshouldcallthefunctionmorethanonce:
day = int(input()) # 4
month =
input() #
October
Brilliant!Whythisdate?It'ssimple:
print('Cinnamon roll day is celebrated on', month, day)
#CinnamonrolldayiscelebratedonOctober4
1.5.4Conclusion
Congratulations, now you know
how
to
work
with
input() , that
is,
a function
that
helps
you interact with
theuser.Believeus,thisissomethingyouwilldefinitelyappreciatewhenprogramming.
14
1.5.5Practice
Computerscience>Programminglanguages>Python>Basics>Simpleprograms>Takinginput
1.5.5.1U
seri
nput
Whatisauserinput?Selectoneoptionfromthelist:
Thenameoftheuser.
Somedatathecomputerreceivesfromtheuser.(X)
Somedatathecomputerprintstotheuser.
Amessageshowntotheuserbythecomputer.
1.5.5.2A
sa
ni
nteger
Whichlineofcodereadstheuserinputandreturnsitinaprogramasanintegernumber?
Selectoneoptionfromthelist:
str(input())
input()
print(input())
integer(input())
int(input())(X)
1.5.5.3T
hee
ndo
fa
ni
nput
Whendoestheinput()functionstopwaitingforuserinput? Selectoneoptionfromthelist:
Oncetheuserpresses"Enter".(X)
After1hourofwaiting.
Aftertheuserpresses"Esc".
Never.
1.5.5.4I
nput()f
unction
Whatdoestheinput()functiondo?Selectoneoptionfromthelist:
Readssomedatafromtheuserandreturnsitinaprogramasanintegernumber.
Readssomedatafromtheuserandreturnsitinaprogramasafloatnumber.
Readssomedatafromtheuserandprintsit.
Readssomedatafromtheuserandreturnsitinaprogramasastring.(X)
1.5.5.5W
hatt
oe
xpect?
Whatwilltheprogramdowhenrunningintothefollowinglineofcode?Selectoneoptionfromthelist:
input('
Say "hi":
')
Wait10secondsandcontinueexecutingthecode
Print"hi"andcontinueexecutingthecode
Waittilltheuserpressesanykey
Waitfortheusertowrite"hi"
PrintSay"hi":andwaittilltheuserpressesEnter(X)
1.5.5.6S
um
Write
a program
that
prints
the
sum
of
three
integer
numbers. Read each number from the input separately
anddon'tspecifyanymessageintheinput,please.
SampleInput1: 3 6 8 SampleOutput1: 17
Solution:
a= int(input ())
b= int(input ())
c= int(input ())
print (a
+ b+ c)
1.5.5.7T
rickyq
uestion
Whatwillbetheoutputforthefollowingpieceofcode?Selectoneoptionfromthelist:
print
("Entera
n
umber:"
)
user_num=
input
()
#u
serenters1
0
15
print
(user_num+
u
ser_num)
20
1010(X)
Error
user_num+user_num
Remember,input()readsasastring,notinteger.
1.5.5.8S
umo
ft
wof
loats
Writeaprogramthatreadstwofloatnumbersfromtheuser(usethefloat())andprintstheirsum.
SampleInput: 8.77 11.25 SampleOutput: 20.02
Solution: a=
float (input ())
b=
float(i
nput())
print
(a
+
b)
1.5.5.9D
atat
ype
Let'ssaywereadauser'sinput:
user_inp=
input
()
Whichdatatype(s)canbenowcontainedinthevariableuser_inp?Selectoneormoreoptionsfromthelist:
Floatnumber
Integernumber
String(X)
Boolean
1.5.5.10T
est
Let's
see
how
it
works. Copy the following code and paste it below. Then change one of the lines so that the
programwouldprintanydatatheuserinputswithoutperforminganyoperationsonthem.
data=
.
..
print
(data)
SampleInput1:10 SampleOutput1:10
1.5.5.11W
ayst
or
ead
Whataretherightwaystoreadtheuser'sinput?Selectoneormoreoptionsfromthelist:
input("Writewhatyouwant:")(X)
writeline("Writewhatyouwant:")
print("Writewhatyouwant:")
input()(X)
1.5.5.12D
ifference
Writeaprogramthatreadstwointegernumbersfromuserandthenprintstheirdifference.
Don'tspecifyanymessagewhenreadingtheinput,please.
SampleInput1: 8 11 SampleOutput1: -3
Solution: a=int(input())
b=int(input())
print (a
- b
)
1.5.5.13C
atchys
ong
Have you
ever
dreamed of
becoming a songwriter? It's time to make a hit. We will leave a verse for later and
writethechoruspartinstead.
All
you need
to
do
is
to
read the
input
number
n and an input word (they are given on separate lines) and to
repeatthiswordexactlyntimes.Don'tspecifyanymessagewhenreadingtheinput.
Finally,printyoursongforus,please!
SampleInput: 7 la SampleOutput: lalalalalalala
Solution:
N=i nt (input ())
word= ( input ())
print (N* word )
16
1.6THEORY:Programwithnumbers
Programs in which there's nothing to calculate are quite rare. Therefore, learning to program with numbers is
never a bad
idea.
An
even
more
valuable skill
we
are
about to
learn
is
the
processing of
user data. With its
help,youcancreateinteractiveandbyfarmoreflexibleapplications.Solet'sgetstarted!
1.6.1Readingnumbersfromuserinput
Since you have become familiar with the input() function in Python, it's hardly new to you that any data
passed to
this
function
is
treated
as
a string. But
how should we deal
with numerical values? As
a general
rule,theyareexplicitlyconvertedtocorrespondingnumericaltypes:
integer
=
int(input())
floating_point
=
float(input())
Pay attention to
current best practices:
it's
crucial
not
to
name your variables as
built-in types (say, float or
int).
Also,
we should take into
account
user mistakes: if
a user
types an
inaccurate input, say,
a string 'two'
instead of a number 2, a ValueError
will
occur.
At
the
moment, we
won't focus
on
it;
but
don't worry, more
information about errors is available in a dedicated topic. Now, consider a more detailed and pragmatic
exampleofhandlingnumericalinputs.
1.6.2Freeairmiles
Imagine you have
a credit card
with
a free
air
miles
bonus program (or
maybe you
already have
one). As a
user,
you
are
expected to
input
the
amount of
money you
spend on average from this card per month. Let's
assume that the bonus program gives you 2 free air miles for every dollar you spend. Here's a simple
programtofigureoutwhenyoucantravelsomewhereforfree:
#
the
average
amount
of
money
per
month
money
=
int(input("How
much
money
do
you
spend
per
month:
"))
#
then
umber
of
miles
per
unit
of
money
n_miles
=
2
#
earned
miles
miles_per_month
=
money
*
n_miles
#
the
distance
between
London
and
Paris
distance
=
215
#
how
many
months
do
you
need
to
get
#
a
free
trip
from
London
to
Paris
and
back
print(distance
*
2
/
miles_per_month)
Thisprogramwillcalculatehowmanymonthsittakestotraveltheselecteddistanceandback.
Although it is recommended to write messages for users in the input()
function, avoid them in our
educationalprogrammingchallenges,otherwiseyourcodemaynotpassourtests.
1.6.3Advancedformsofassignment
Whenever you use an
equal
sign
=,
you
actually
assign
some value to a name. For that reason, = is typically
referred to as an assignment operator. Meanwhile, there are other assignment operators you can use in
Python. They are also called compound assignment operators, for they carry out an arithmetic operation
andassignmentinonestep.Havealookatthecodesnippetbelow:
number
=
10
number
=
number
+
1
#
11 #
simple
assignment
Thiscodeisequivalenttothefollowingone:
number
=
10
number
+=
1
#
11 #
compound
assignment
17
One can
clearly
see from
the
example
that
the
second piece of
code
is
more
concise (for it
doesn't
repeat
thevariable'sname).
Naturally, similar assignment forms
exist
for
the
rest
of
arithmetic operations: -=,
*=,
/=,
//=, %=,
**=.
Given
theopportunity,usethemtosavetimeandeffort.
Onepossibleapplicationofcompoundassignmentcomesnext.
1.6.4Countervariable
In programming, loops are used alongside special variables called counters.
A counter
counts how
many
times a particular code is run. It
also
follows
that
counters
should
be
integers.
Now we
are
getting
to
the
point:youcanusetheoperators+=and-=toincreaseordecreasethecounterrespectively.
Considerthisexamplewhereauserdeterminesthevaluebywhichthecounterisincreased:
counter
=
1
step
=
int(input()) #
let
it
be
3
counter
+=
step
print(counter)
#
it
should
be
4,
then
In
case
you need
only
non-negative integers from the user (we are increasing the counter after all!), you can
prevent
incorrect inputs
by
using
the abs()
function. It
is
a Python built-in function that returns the absolute
valueofanumber(thatis,valueregardlessofitssign).Let'sreadjustourlastprogramabit:
counter
=
1
step
=
abs(int(input()))
#
user
types
-3
counter
+=
step
print(counter)
#
it's
still
4
Asyoucansee,thankstotheabs()functionwegotapositivenumber.
For now, it's all right that you do not know much about
the
mentioned details
of
errors,
loops
and
built-in
functions in Python. We will catch up and make sure that you know these topics comprehensively. Keep
learning!
1.6.5Conclusion
Thus, we have shed some light on new details about integer arithmetic and the processing of numerical
inputsinPython.Feelfreetousetheminyourfutureprojects.
An
airline
company "Happy travel" has a loyalty system for its customers: for each spent dollar they get 0.01
free miles on their account and then can use them to travel for free. Below is
the
code
for
free
air
miles
calculationforonecustomerwhoplanstotravelfromLondontoParisandback:
#
the
number
of
free
miles
per
dollar
n_miles
=
0.01
#
money
spent
per
month
(in
dollars)
money
=
2000
#
number
of
miles
earned
each
month
miles_per_month
=
money
*
n_miles
#
distance
from
London
to
Paris
and
back
(in
miles)
total_distance
=
215
*
2
1.6.6Practice
Computerscience>Programminglanguages>Python>Basics>Simpleprograms>Programwithnumbers
1.6.6.1B
ado
men
Takealookatthecodebelow:
step = 666
counter += step
18
print(counter)
It'snotworkingforsomereason.What'swrongwithit?Selectoneoptionfromthelist:
Thestepvalueshouldbeafloating-pointnumber.
Thestepvalueisextremelylarge.
Oneofthevariableshasn'tbeendefined. (X)
Thecompoundassignmentoperatorshouldbe=+.
1.6.6.2U
ndercover
Whichofthefollowingoperatorshasnothingtodowithcompoundassignment?
Selectoneoptionfromthelist:
+=
-=
**=
//=
%=
== (X)
Welldone!Theequalityoperator`==`isusedtocomparevalues,nottoassignthem.
1.6.6.3W
heny
ou'llh
avea
f
reet
rip?
An
airline
company "Happy travel" has a loyalty system for its customers: for each spent dollar they get 0.01
free miles on their account and then can use them to travel for free. Below is
the
code for
free air
miles
calculationforonecustomerwhoplanstotravelfromLondontoParisandback:
#the number of free miles per dollar
n_miles = 0.01
#money spent per month (in dollars)
money = 2000
#number of miles earned each month
miles_per_month =
money * n_miles
#distance from London to Paris and back (in miles)
total_distance =215 *2
What would be the correct final line to calculate how many months it
will
take
for
this
client to
make the
desiredtripfreeofcharge?Selectoneoptionfromthelist:
total_distance*2/miles_per_month
total_distance/miles_per_month
total_distance*2
total_distance*miles_per_month
1.6.6.4C
alculatinga
ne
xpression
Write a program that reads an integer value n from the standard input and prints the result of the
expression:
((n+
1
)*
n
+
2
)*
n
+
3
SampleInput1: 3 SampleOutput1: 45
Solution:
n
=
int
(i
nput
())
print
(((
n+
1)
*n
+2
)
*n
+3
)
1.6.6.5T
hel
astd
igito
fa
n
umber
Writeaprogramthatreadsanintegerandoutputsitslastdigit.
SampleInput1: 425 SampleOutput1: 5
Hints:
19
Ihadtodoabitofgooglingandfoundthat%10willalwaysgivethelastdigitofanumber.
you'llwanttheusertoinputanumber,butmakesureitsaninteger.
last_digit=number%10 #having%10willALWAYSgiveonlythelastdigit.
lastly,printthelast_digit
number = ....
last_digit = number %10
print(.....)
Solution:
number01= i nt (i
nput ())
last_digit= n umber01% 1 0
print (last_digit )
Outrasresoluções:
a =i
nt (i
nput ())
print
(a
%1
0
)
____
number
=l
ist
(s
tr
(i
nput
()))
print
(number[
-1
])
____
num=
l
ist
(i
nput
('
'
))
last_index=
n
um[
-1
]
print
(last_index)
____
input_number=
i
nt
(i
nput
()) #
p
uty
ourp
ythonc
odeh
ere
print
(s
tr
(input_number)[
-1
])
____
n=
i
nput
()
print
(n[
-1
])
____
n=
i
nput
() #
t
akea
n
umbera
ss
tring
print
(n[
-1
]) #
p
rintt
het
hel
astc
hari
nt
hes
tringi
ndex>
-
1
____
print
(i
nput
()[
-1
])
1.6.6.6C
alculatingS
V
P
Ask
the
user about parameters of a rectangular parallelepiped (3 integers representing the length, width and
height)andprintthesumofedgelengths,itstotalsurfaceareaandvolume.
Sumoflengthsofalledges: s=4(a+b+c)s=4(a+b+c)
Surfacearea: S=2(ab+bc+ac)S=2(ab+bc+ac)
Volume: V=abc
Solution:
a=i nt (input ())
b=i nt (input ())
c=i nt (input ())
len_edges= 4
*( a+
b+
c )
area_surf= 2
*( (a*b
)
+ ( b
* c)+ ( a*
c)
)
vol_par= a *
b* c
20
print(l en_edges )
print(a rea_surf )
print(v ol_par)
Outrasresoluções:
print
(( lambda
a, b,
c:
(f
"{4
*
(a
+
b
+
c)}\n{2
*
(a
*
b
+
b
*
c
+
c
*
a)}\n{a
*
b
*
c}"
))(
int
(i
nput
()),i
nt
(i
nput
()),i
nt
(i
nput
())))
____
a,b
,c
=
i
nt
(i
nput
()),i
nt
(i
nput
()),i
nt
(i
nput
())
print
("
{}\n{}\n{}"
.f
ormat
(4
*
(
a+
b
+
c
),
2*
(
a*
b
+
b
*
c
+
a
*
c
),a
*
b
*
c
))
____
a,b
,c
=
i
nt
(i
nput
()),i
nt
(i
nput
()),i
nt
(i
nput
())
s=
4
*
(
a+
b
+
c
)
S=
2
*
(
(a*
b
)+
(
b*
c
)+
(
a*
c
))
V=
a
*
b
*
c
print
(s,S
,V
,s
ep= )
"\n"
1.6.6.7D
ividen
utse
quallyb
etweens
quirrels
N squirrels found K nuts and decided to divide them
equally.
Determine
how
many
nuts
each
squirrel
will
get.
Inputdataformat:TherearetwopositivenumbersNandK,eachofthemisnotgreaterthan10000.
SampleInput1: 3 14 SampleOutput1: 4
Solution:
N= int(input ())
K= int(input ())
print (K//N )
Outrasresoluções:
n= int(i
nput ())
print
(i
nt
(i
nput
())/
/n
)
____
N=
a
bs
(i
nt
(i
nput
()))
K=
a
bs
(i
nt
(i
nput
()))
print
(K/
/N
)
1.6.6.8T
hef
irstd
igito
fa
t
wo-digitn
umber
Writeaprogramthatwilltakeaninputofatwo-digitintegerandprintitsfirstdigit(i.e.thenumberoftens).
SampleInput1: 42 SampleOutput1: 4
Solution:
que=i nt (i
nput ())
print (que/ /10)
Outrasresoluções:
number= input
()
print
(number[
0]
)
____
print
(i
nput
()[
0]
)
21
1.6.6.9 Difference of times
You will
get the values for two moments in
time
of the same day: when Megan went for a walk, and when it
started to rain. It is known that the first event happened earlier than the
second one. Find
out
how
many
secondspassedbetweenthem.
The program gets the input of
six
integers, each on a separate line. The first three integers represent hours,
minutes, and seconds of the first
event, and the
rest three
integers define similarly the
second event.
Print
thenumberofsecondsbetweenthesetwomomentsoftime.
SampleInput1: 1 1 1 2 2 2
SampleOutput1: 3661
SampleInput2: 1 2 30 1 3 20
SampleOutput2: 50
Solution:
hour1= i nt (input ())
min1= i nt (input ())
sec1= i nt (input ())
hour2= i nt (input ())
min2= i nt (input ())
sec2= i nt (input ())
first_event= ( h our1* 3 600 )+ ( min1* 6 0 )+
s ec1
second_event= ( h our2* 3 600 )+ ( m in2* 6 0 )+s ec2
print (second_event- f irst_event )
Outrasresoluções:
hour1= int (input ())
minute1=
i
nt
(i
nput
())
second1=
i
nt
(i
nput
())
time_1=
h
our1*
3
600
+
m
inute1*
6
0
+
s
econd1
hour2=
int
(i
nput
())
minute2=
i
nt
(i
nput
())
second2=
i
nt
(i
nput
())
time_2=
h
our2*
3
600
+
m
inute2*
6
0
+
s
econd2
print
(a
bs
(time_1-
t
ime_2))
____
print (a
bs
(hours_2
*
3600
+
minutes_2
*
60
+
seconds_2
-
hours_1
*
3600
-
minutes_1
*
60
-
seconds_1))
22
hundreds=
n
/
/
100
tens=
(
n%
1
00
)/
/1
0
units=
n
%
1
0
print
(hundreds+
t
ens+
u
nits)
____
n=
i
nt
(i
nput
())
print
(n/
/1
00
+
n
%
1
00
/
/1
0
+
n
%
1
0
)
____
n=
i
nt
(i
nput
())
print
((
int
(n/
1
00
))+
(
(n/
/1
0
)%
1
0
)+
(
n%
1
0
))
____
number=
i
nt
(i
nput
())
a=
n
umber/
/1
00
b=
n
umber/
/1
0
-
a
*
1
0
c=
n
umber%
1
0
print
(a+
b
+
c
)
____
print
(s
um
([
int
(x)f
or
x
i
n
s
tr
(i
nput
())]))
*Correct,butcanbeimproved.1codestyleerror
____
number=
s
tr
(i
nput
())
count=
0
for
i
i
n
n
umber:
count+
=i
nt
(i)
print
(count)
____
num=
s
tr
(i
nput
())
f=
n
um[
0]
s=
n
um[
1]
t=
n
um[
2]
f=
i
nt
(f)
s=
i
nt
(s)
t=
i
nt
(t)
res=
f
+
s
+
t
print
(res)
1.6.6.11P
umpkinp
ie
Paulhasbakedapumpkinpieandaskedhisguestshowmanypiecestheywantedtotakehome:
n_pieces = int(input("How many pieces of the pumpkin pie can I offer you?"))
It's so nice of him! However, this program crashed as one guest
entered the
value 2.5.
What are
possible
actionstopreventtheerrorinthecode?Thereismorethanjustonecorrectanswer.
Let's assume that no guest should leave without
a treat!
You
also
don't
have to
think about cases when
a
guestenterssomethingdifferentthananumberinthistask.Selectoneormoreoptionsfromthelist:
Leavethewholepieforyou.
Converttheinputvaluetof loat ratherthani nt . (X)
Readthenumbersasfloatsandthenroundthemuptotheclosestinteger. (X)
23
Printamessageforthegueststhatpiecesshouldbewhole.
1.6.6.12S
avingsa
ccount
For
the
given
amount of money, calculate the income from this savings account with a 5% interest rate after
oneyear.
Savetheresultintothevariableincome.YouDONOTneedtoprintit.
Solution:
amount= 1000
interest_rate= 5
years= 1
income= (amount* ( interest_rate/ 1 00
))
1.6.6.13G
oodr
esto
nv
acation
Write a program that will help people who are going on vacation. The program
should
calculate
the
total
requiredsum(e.g.$)ofmoneytohaveagoodrestforagivenduration.
Therearefourparametersthathavetobeconsidered:
● durationindays
● totalfoodcostperday
● one-wayflightcost
● costofonenightinahotel(thenumberofnightsisequaltothedurationofdaysminusone)
Readintegervaluesoftheseparametersfromthestandardinputandthenprinttheresult.
SampleInput1: 7 30 100 40
SampleOutput1: 650
Solution:
n_days= abs
(i nt (i nput ()))
food_day= a
bs (i
nt (i nput ()))
flight= abs
(i nt (i nput ()))
h_per_night= a bs (int (i
nput ()))
hotel_total= a bs (int (n
_days- 1)
* h _per_night )
print (( n_days* food_day )+
(f light* 2)
+ h otel_total )
1.6.6.14D
esks
A school has decided to create three new math groups and equip three classrooms for them with new
desks. Your task is to calculate the minimum number
of
desks to
be
purchased. To do
so,
you'll
need
the
followinginformation:
● The number of students in each of the three groups is known: your program will receive three
non-negative integers as
the
input. It is possible that one or more of them will be zero, so you should
takeitintoaccount.
● Each group will sit
in
its
own classroom. It means that you should calculate the number of desks for
eachclassroomseparately,andonlythenaddthemup!
● At most two students may sit at any desk. You are expected to output the minimum number of
deskstobuy,sothereshouldbeasmanyaspossibledeskstakenbytwostudentsratherthanone.
Mostprobably,you'llneedoperations//and%inyourprogram!
SampleInput1: 20 21 22
SampleOutput1: 32
SampleInput2: 16 18 20
SampleOutput2: 27
Solution:
stud_01= a bs (i nt (i nput ()))
stud_02= a bs (i nt (i nput ()))
stud_03= a bs (i nt (i nput ()))
print ((stud_01/ /2 + s tud_02/ /2 + stud_03/ /2 )
+
( stud_01% 2 + s tud_02% 2 + s tud_03% 2) )
24
1.7T
HEORY:C
ommandlinea
rguments
1.7.1Runningfromthecommandline
Using the command line
is
sometimes very useful in the programmer's work. And Python scripts can be run
from the command line just like its regular commands, e.g. "cd" or "mkdir". This means we can write a
modulethat,forexample,multipliestwonumbersandnicelyprintstheresult,andrunitfromtheshell:
pythonm ultiply_two_numbers.py5 9
In
the line above,
python is kind
of a
command that
indicates that the Python interpreter should be
used for the
following script. In
some cases, the system may already know how to run .py files but
we will not go into details here and, for the sake of consistency, will use the python command
throughoutthistopic.
imports
ys # f
irst,wei
mportt hemodule
args=
sys.argv # weg
etthel
isto fa
rguments
first_num= float
(args[1]
) #c
onverta rgumentstof
loat
second_num= f
loat(args[
2])
product= f
irst_num* s
econd_num
print
("
Thep roducto f"
+
args[1]
+
"t
imes"
+
args[
2]+
"
e
quals"
+
s
tr
(product))
1.7.3Checkingtheinput
It is also worth mentioning that if we expect to get a
specific number of
arguments (i.
e.
almost
always), it is a good idea to check the length of sys.argv in the program. Let's
check that in
our
scriptm ultiply_two_numbers.py:
import
s
ys
args=
sys.argv
25
ifl
en (args)! =3:
p
rint ("Thescriptshouldbecalledwithtwoarguments,thefirstandthesecondnumbertobemultiplied")
else :
first_num= float (args[ 1]
)
second_num= float (args[ 2] )
product= first_num* s econd_num
p
rint ("Thep roducto f" +
a rgs[1]
+ " t
imes"
+args[ 2]+"equals" +s
tr (product))
So,thisishowourscriptwilllooklikefromthecommandline:
1.7.4WithintheIDE
Let's take
a look
at
PyCharm's
capabilities in comparison to
the command line. Instead of manually writing
the script name and arguments each time,
you can
set
them in
the
configuration. For
this
in
the
Run
area
selectE ditConfigurationst oopentheRun/DebugConfigurationsdialog.
If
you
do
not
see
a similar
area
in
your
IDE,
then
make
it
visible
through View -> Appearance -> Navigation
Bar.YoucanreadmoreonhowtodoitintheJ etBrainsdocumentation.
Congratulations, you got
into
the Run/Debug Configurations! In the
Parameters fi
eld,
we can set the
argumentsthatwewouldwriteinthecommandlineseparatedbywhitespaces.
Savechangesandrunthescript.Theoutputwouldbeasexpected:
Thep
roducto
f3
t
imes5
e
quals1
5.0
Now, instead of running the module from the shell as python multiply_two_numbers.py 3 5 and
passing arguments each
time it
is
called,
you
can set them in the Parameters field and just run the
programinPyCharm.
26
1.7.5Summary
We have learned how to run Python scripts from the command line, how to get access to the passed
arguments from the
program itself,
as
well
as
that
it's
important
to
check that
the
arguments are
what we
expect them to be. We also
got acquainted with
PyCharm's capabilities
for
specifying script
arguments in
configurations.Thisknowledgewilldefinitelyhelpyouinyourfurtherprogrammer'spath!
1.7.6Practice
Computerscience>Programminglanguages>Python>Basics>Simpleprograms>Commandlinearguments
1.7.6.1L
ength
Whatwillbethelengthofsys.argvinthefollowingexample:pythonscript.py-13file.txt?
1.8THEORY:Argparsemodule
If
you're writing a
user-friendly program, one way to
make it more universal is to use the command
line and let
users specify all
the necessary parameters and their
values themselves. By doing that,
you design a
program capable of
taking different numbers if it's a calculator, for example, or a path
to
a
file,
as
it's
often required, without making the
user
go inside the script trying to find where and
whatshouldbereplaced.
The argparse is one of the modules that lets you do that. It allows you to pass the arguments
through the command line and also assign names to them, use them as “flags”, automatically
generatemessagesforusers,anddoalotofothercoolthingswewillgettoabitlater.
We will write a script called recipe_book.py as an example that takes up to five ingredients and
printsarecipeofadishyoucancookwiththeprovidedingredients.
1.8.1Gettingstartedwithargparse
Thefirstthingistoimportthemodule:
importa
rgparse
parser= a
rgparse.ArgumentParser(description="Thisp rogramp rintsr ecipes\
consistingo ft
hei ngredientsy ouprovide.")
The A rgumentParser has quite a number of parameters that you can specify,
but
we only
invoked
description which
is
quite
handy in
order
to
explain
to
a
user
what your program is
for in general.
Nowlet'saddsomearguments.
1.8.2Addingarguments
Todothat,wewillusethea dd_argument()method:
parser.add_argument(
"-i1"
,"
--ingredient_1"
) #
o
ptionala
rgument
#
o
r
parser.add_argument(
"ingredient_1"
) #
p
ositionala
rgument
We also need to note the difference between the optional and the positional arguments. When
parsing, if an argument has a dash - or a double dash -- prefix,
it'll
be
treated
as
optional.
Let's
take a closer look at the first line of the code in the example above. With optional arguments,
traditionally, a single dash - denotes a short version of a name (usually consisting of only one
27
letter), while a double dash -- is used for a full argument name. When specifying this
argument
from
the command line,
you
can use either of these variants.
Since
positional arguments are used
withoutaprefixbeforethem,theycanhaveonlyonename.
The add_argument() has a lot of useful parameters, but we are going to look at the most
commonly-used ones.
For
example, the
parameter “action” is
responsible
for what should be done
with a
command-line argument. By
default, it
just
stores the value passed to the argument, though
it'snottheonlyoption.
parser.add_argument(
"--salt"
,a
ction=
"store_true"
)
Since pretty much everybody has some salt in their kitchen, we'll assume that our users always
have salt on hand. So, instead of making users specify salt as one of
the
numbered ingredients,
we'll let them toggle its presence in the recipe with a
simple flag.
In the example
above, we
have
done so by setting the action to the “s tore_true ”. It is used to assign boolean values to the
corresponding arguments. The s alt value will be F alse by default but if the user lists - -salt among
the
arguments, the
value will
be changed to
T rue. There's also an opposite option, s tore_false: the
argument'sdefaultvaluewillbeTrue,butitwillbemadeF alseiftheargumentislisted.
For action = "store_false": the default value is True. For action = "store_true": the
default
value
is
False.
Thesamecanbeachievedbyspecifyingthed efaultparameter:
parser.add_argument(
"--pepper"
,d
efault=
False
)
This
time
the
argument isn't
used
as
a flag
any
more,
so,
if
you'd
like
to
change
the
value,
you will
havetodefineitinthecommandlineexplicitly:- -pepper"True".
Finally, since we're only at the beginning of the development process of our
program, it
might be
useful to limit the choice of each ingredient to only those used in our recipes. This
can be
done
withthec hoicesparameterthatwillshowtheacceptablevaluesforaparticularargument:
parser.add_argument("-i2","
--ingredient_2",
choices=["pasta","
rice","
potato","
onion",
"garlic","
carrot","
soy_sauce","
tomato_sauce"],
help="Youn
eedt
oc
hooseo
nlyo
nei
ngredientf
romt
hel
ist.")
Another useful
parameter you
see here
is
help
. It
contains a brief description of an argument and
alsoallowsyoutoguideauserintheirworkwithascript.
1.8.3Parsingarguments
Thep arse_args()methodisusedforreadingargumentstringsfromthecommandline:
print
(args.ingredient_2) #
onion
#(
thev
aluew
asc
hosenb
ya
u
serf
romt
heg
iveno
ptions)
Notethatwecan'tuseshortversionsofarguments:forexample,args.i2w
illn
otwork.
28
In
case
a user
didn't
specify
an
optional
argument
in the command line, the value is set to None
by
default:
print
(args.ingredient_3) #
None
#
(the value wasn't provided by a
user)
Sofar,thecodeofourprograminthe“recipe_book.py”modulelooksasfollows:
import
argparse
parser= a
rgparse.ArgumentParser(description= "Thisp rogramp rintsrecipes\
consistingo fthei
ngredientsy oup rovide.")
parser.add_argument( "-i1"
,"--ingredient_1" ,choices=[ "pasta","rice"
,"potato" ,
"
onion","
garlic" ,"carrot","soy_sauce" ,"
tomato_sauce" ],
h
elp
="
Youneedt oc
hooseonlyo nei ngredientf romthel
ist." )
parser.add_argument( "-i2"
,"--ingredient_2" ,choices=[ "pasta","rice"
,"potato" ,
"
onion","
garlic" ,"carrot","soy_sauce" ,"
tomato_sauce" ],
h
elp
="
Youneedt oc
hooseonlyo nei ngredientf romthel
ist." )
parser.add_argument( "-i3"
,"--ingredient_3" ,choices=[ "pasta","rice"
,"potato" ,
"
onion","
garlic" ,"carrot","soy_sauce" ,"
tomato_sauce" ],
h
elp
="
Youneedt oc
hooseonlyo nei ngredientf romthel
ist." )
parser.add_argument( "-i4"
,"--ingredient_4" ,choices=[ "pasta","rice"
,"potato" ,
"
onion","
garlic" ,"carrot","soy_sauce" ,"
tomato_sauce" ],
h
elp
="
Youneedt oc
hooseonlyo nei ngredientf romthel
ist." )
parser.add_argument( "-i5"
,"--ingredient_5" ,choices=[ "pasta","rice"
,"potato" ,
"
onion","
garlic" ,"carrot","soy_sauce" ,"
tomato_sauce" ],
h
elp
="
Youneedt oc
hooseonlyo nei ngredientf romthel
ist." )
parser.add_argument( "--salt",action= "store_true" ,
h
elp
="
Specifyi fyou'dliketou sesaltinyourr
ecipe." )
parser.add_argument( "--pepper" ,default= "False",
h
elp
="
Changet o'True'ifyou'dl iketousepepperiny
ourr ecipe."
)
args= p
arser.parse_args()
ingredients= [args.ingredient_1,a rgs.ingredient_2,a rgs.ingredient_3,
a
rgs.ingredient_4,a rgs.ingredient_5]
if
a
rgs.salt:
ingredients.append( "salt")
if
a
rgs.pepper= ="
True"
:
ingredients.append( "pepper" )
print (f
"Thei
ngredientsyouprovideda re:{ingredients}" )
deff
ind_a_recipe(ingredients):
...
#
processesthei
nputandreturnsa recipedependingo ntheprovidedingredients
1.8.4Howdoyouactuallyusethatinthecommandline?
Now let's
see
how
it
looks
like
from the user perspective. Here's a sample call of our program from
thecommandline:
29
pythonr ecipe_book.py- i1rice-i2o nion-i3garlic-i4carrot-i5tomato_sauce- -salt
#Theingredientsyouprovidedare:['rice','onion','garlic','carrot','tomato_sauce','salt']
#<Thed escriptiono ftheavailabler ecipe>
What'simportanttonotehereisthattheformatargument
valueand
argument=value
areequivalent:
pythonr ecipe_book.py- i1=pasta- i2=garlic- i3=tomato_sauce- -salt- -pepper="True"
#Theingredientsyouprovidedare:['pasta','garlic','tomato_sauce',None,None,'salt','pepper']
#<Thed escriptiono fthea vailabler ecipe>
However, if
a
user
tries
to
use
an
option
which
is
not given in the choices parameter, it will raise an
error:
pythonr
ecipe_book.py- -help
#u
sage:recipe_book.py[ -h]
# [
-i1{pasta,rice,potato,onion,garlic,carrot,soy_sauce,tomato_sauce}]
# [
-i2{pasta,rice,potato,onion,garlic,carrot,soy_sauce,tomato_sauce}]
# [
-i3{pasta,rice,potato,onion,garlic,carrot,soy_sauce,tomato_sauce}]
# [
-i4{pasta,rice,potato,onion,garlic,carrot,soy_sauce,tomato_sauce}]
# [
-i5{pasta,rice,potato,onion,garlic,carrot,soy_sauce,tomato_sauce}]
# [
--salt][ --pepperPEPPER]
#
#T
hisp
rogramprintsrecipesc onsistingoft
heingredientsyoup
rovide.
#
#o
ptionalarguments:
# -h,--help
showthishelpm
essageandexit
# -i1{pasta,rice,potato,onion,garlic,carrot,soy_sauce,tomato_sauce},- -ingredient_1
#{
pasta,rice,potato,onion,garlic,carrot,soy_sauce,tomato_sauce}
# Y
ouneedt
ochooseonlyonei
ngredientfromt
hel
ist.
# -i2{pasta,rice,potato,onion,garlic,carrot,soy_sauce,tomato_sauce},- -ingredient_2
#{
pasta,rice,potato,onion,garlic,carrot,soy_sauce,tomato_sauce}
# Y
ouneedt
ochooseonlyonei
ngredientfromt
hel
ist.
30
# -i3{
pasta,rice,potato,onion,garlic,carrot,soy_sauce,tomato_sauce},- -ingredient_3
#{
pasta,rice,potato,onion,garlic,carrot,soy_sauce,tomato_sauce}
# Y
oun
eedtoc
hooseo
nlyoneingredientfromt
helist.
# -i4{
pasta,rice,potato,onion,garlic,carrot,soy_sauce,tomato_sauce},- -ingredient_4
#{
pasta,rice,potato,onion,garlic,carrot,soy_sauce,tomato_sauce}
# Y
oun
eedtoc
hooseo
nlyoneingredientfromt
helist.
# -i5{
pasta,rice,potato,onion,garlic,carrot,soy_sauce,tomato_sauce},- -ingredient_5
#{
pasta,rice,potato,onion,garlic,carrot,soy_sauce,tomato_sauce}
# Y
oun
eedtoc
hooseo
nlyoneingredientfromt
helist.
# --salt S
pecifyi
fyou'dl
iketou
sesalti
ny
ourrecipe.
# --pepper C
hanget
o'True'i
fyou'dliket
ou
sepepperiny
ourr
ecipe.
Again, first we see the 'usage' of our program, then, there's the description we wrote, and, finally, the
listofallarguments.
1.8.5Summary
In this topic, we briefly
familiarized ourselves with
Python argparse module. There
are
three
main
steps to get the job done: first, create the ArgumentParser object; then, add arguments with
add_argument() method; finally, parse them by p arse_args() method and use in your program. Since
what we discussed here is
more
of
a review
than a
full description, it's definitely worth reading the
official docs, argparse section for more details, especially to learn about different parameter
optionsyoucanuseinyourprogram.
1.8.6Practice
Computerscience>Programminglanguages>Python>Basics>Simpleprograms>Argparsemodule
1.8.6.1A
rgumentsa
sf
lags
Yourtaskistocompletethefollowingcode.
Add the --print_answer argument and
use
the
actionparameter.
The
argument's
value
should
be
False iftheargumentisnotlisted,and T
rueo therwise.
import a rgparse
parser= a rgparse.ArgumentParser()
31
2M
ODULEA
NDP
ACKAGES
2.1THEORY:Loadmodule
2.1.1Modulebasics
While working on
simple examples, you probably type your code directly into
the interpreter. But every time
you
quit from the
interpreter and start it
again, you lose all
the definitions you made before. So as you start
writing larger programs, it
makes sense to prepare your code in
advance using a text editor and then run it
with the interpreter. A file containing a list of operations that will be further on read and interpreted is called
script.
You also may want to write some functions and then use them in other programs or even reuse code
someone else wrote before. One way is just to
copy the code into your program, but
it
soon leads to
code
that is
bad-structured and hard to read. Luckily, there is
another way in
Python to organize and reuse code
calledm odules.
The
module is simply a file that contains Python statements and definitions. It usually has a . py extension.
Whatreallymakesthemodulesystempowerfulistheabilitytoloadorimportonemodulefromanother.
2.1.2Moduleloading
To load a module, just use an import statement. In its basic form, it has the following syntax:
importm odule .
import
s
uper_module
super_module.super_function() # c allinga f
unctiond efinedi ns uper_module
print
(super_module.super_variable) # a
ccessinga v ariabled efinedi ns
uper_module
is the name of the module you want to import. For example, a file called
super_module
super_module.py has a name super_module . In order to be available for import,
super_module.py should be located
in
the
same directory as the file
you are
trying
to import it
from. At first, Python importing system looks for
a module in
the current directory, then it
checks
the built-in modules, and if nothing is found an error will be raised. After importing, the module
becomes available under its
name and
you can access functions and variables defined in it
using
thedotnotation.
It's
also
common to
only
import
required functions
or
variables
from
a
module but not the module
itself.Youcandothisbyusingaf romformofimportstatement.
from
super_modulei
mport
super_function
super_function() #
s
uper_functionisn
owavailabledirectlyatthec
urrentm
odule
super_module.super_function()
#
note,
that
in
this
case
name
super_module
is
not
imported,
#
s
othislinel
eadstoa
ne
rror
A
good
practice is
to
load
a
single
module
in
a single line and put all your imports at the top of the
filebecauseitincreasesreadability.
import
module1
import
module2
import
module3
32
#t
her
esto
fm
odulec
odeg
oesh
ere
A special form of import statement allows you to load all the names defined in a module. It is
called wildcard import and
has
the
syntax
from
module import *. You should generally avoid this
in your code. It can cause unexpected behavior because you don't know
what names exactly
are
imported into the current namespace. Besides, these names may shadow some of the existing
oneswithoutyourknowledge.It'sbettertomakeitexplicitandspecifywhatyou'reimporting.
Incaseyouhavetouseseveralimportstatements,payattentiontotheirorder:
1. standardlibraryimports
2. thirdpartydependencyimports
3. localapplicationimports
Having your imports grouped, you may put a blank line between import sections. Also, some
guidelines,includingours,recommendsortingimportsalphabetically
2.1.3Built-inmodules
Python
comes with
a great
standard library.
It
contains a lot of built-in modules that provide useful
functions
and
data structures. Another advantage is
that
the standard library
is
available
on
every
systemthathasPythoninstalled.H ereyoucanfindanofficiallibraryreference.
Pythonhasamath
modulethatprovidesaccesstomathematicalfunctions.
import
m
ath
print
(math.factorial(5)
) #p
rintsthev
alueo
f5
!
print
(math.log(
10
)) #p
rintsthen
aturallogarithmo
f1
0
print
(math.pi) #
mathalsoc
ontainsseveralc
onstants
print
(math.e)
Thes modulecontainscommonstringoperationsandconstants.
tring
from
s
tringi
mportd
igits
print
(digits) #
p
rintsallt
hed
igits
ymbols
Ther moduleprovidesfunctionsthatletyoumakearandomchoice.
andom
from
r
andomi
mport
c
hoice
print
(choice([
'red','
green'
,'
yellow'
])) #
p
rinta
r
andomi
temf
romt
hel
ist
2.1.4Summary
Thus, in this topic, we've learned what scripts and modules are, why they're useful, and how to
import modules (or particular things from them). We've also discussed external modules and those
that come with a standard Python library. This basic skill will definitely give you a lot of
opportunitiesinthefuture,sodon'tbeshytotrymoduleloadingonyourown!
33
34
3B
UILD-iNS
3.1THEORY:Anyandall
By
now, you certainly know that Python has a lot of different built-in functions that help developers
work more efficiently. Built-in
functions are always available, so you don't need to declare or import
them. Just call such a function whenever you need it. You have already seen one of those
functions, it
is
p
rint() . Today we will learn two more built-in functions any() and all() and find
outhowandwhentousethem.
Be careful though, these functions work only with iterable objects, e.g. strings and
lists.
A
list
is
iterable,sowewilluseittoillustratethetheoreticalpartandtoshowhowa ny() anda
ll() work.
3.1.1Functionany()
The result
of the any() function call is the boolean value: it returns True if an element or a group
of
elements in
an iterable object are evaluated True . Otherwise, it returns False . Let’s take a look
at
the example. Imagine that you and your friends, Jam and Andy, wrote a test and got your results
in
the
form of a
list with
True and False values. The test
is
passed if
at
least one answer is correct.
Nowyouneedtocheckifyouandyourfriendspassedthattest.
andy_results
=
[F
alse
,F
alse
,F
alse]
print
(a
ny
(andy_results)) #
False
Unfortunately, your
friend
Andy failed.
What
about
Jam?
Well,
this
friend
of
yours
didn't
write
the test at all,
sohegotanemptylistofresults.
jam_results
=
[]
print
(a
ny
(jam_results)) #
False
The list doesn't contain any elements, and since no True value is
to
be
found
the
any() function
returnsF alse.
So what does the a
ny() function do? First, it takes a list as an argument, then evaluates all the
elementsofthislisttofindatleastoneT rue,ifso,itreturnsT rue ,otherwise,theresultisF alse .
3.1.2Functionall()
The all() function works pretty much like any() . The difference is that all() function checks if all
the
elements of
an
iterable object
are
True and returns True if
they are.
Otherwise, you get False .
Do you remember the story from the previous section where we checked the results of
the test?
Let's proceed. Imagine yet
another test,
this time the
final one. To
succeed, you should answer all
thequestionscorrectly.Howdiditgothistimeforyouandthetwofriendsofyours?
35
your_results =
[T rue
,F
alse ,F alse ]
print (a
ll (your_results)) # False
As
you can see, not all the answers in your case are correct, so you didn't pass the test. What about
Andy'sresults?
andy_results =
[T rue
,T
rue ,T rue ]
print (a
ll (andy_results)) # True
Luckily,Andypassed.Jamseemstohaveavacation.Hislistofresultsisemptyagain.
jam_results=
[
]
print
(a
ll
(jam_results)) #
T
rue
The list
doesn't
contain
any
elements, but
the
all() function
will
return
True
because
it
searches
foranyF alse
values.NoFalsevaluesresultinT rue
.Becarefulwiththisscenario.
3.1.3Non-booleanvalues
Pay attention to the fact that any()
and all()
can take a list containing non-boolean
values.
Let'srecallhowtheyareevaluated.
Empty sequences,
e.g.
strings
and
lists,
as
well
as
zero,
are
equivalent to
False
, the
same applies
totheconstantN
one.Non-emptysequencesareequivalenttoT rue
.
Becautious,theresultofcallingtheall()
functiononanemptysequencediffersfrom
convertinganemptysequencetoabooleanvalue.Theresultofa ll(list()) is
True ,the
resultof
bool(list()) isF
alse.
Hereisalistwithfalsevalues.any()
anda
ll()
willhavethesamebehaviorinthisexample:
Also,
you
can
turn
the
elements
of
your
list into the boolean values via comparison. Suppose, we have a list
ofscoresandwanttocheckwhethersomeareequalto3orgreater.Itcanbedonelikethis:
scores= [1
, 2,
3 ,
4 ]
boolean_scores= [
score> =3 f or scorei n s
cores] # [ False,F alse,T rue,T rue]
print (a
ny (boolean_scores)) # T
rue
print (a
ll (boolean_scores)) # F
alse
However, lists may contain different elements, e.g. strings or nested lists, in such cases, the
behaviorofa ny() anda ll()woulddependlargelyonthecontents.Keepthatinmind.
3.1.4Conditions
Coders often use any()
and all()
functions in conditions. It helps to check the elements of
iterableobjectsquicklyandtoavoidcomplexconstructions.
36
Let's choose a candy box for Valentine's Day. Each box contains several types of sweets. But you are
interested in the even amount of candies of each type because, obviously, you will share them
with
your
valentine.
box= [ 10
,2 0,3 3
]
ifa
ny ([candy% 2f orcandyi n
box]):
p
rint ("Iti snota properg ift." )
else :
p
rint ("Perfect!" )
Short
and
sweet,
isn't
it? Life is like a box of chocolates! As long as the values you deal with can be
convertedtoT
rueandF alse ,it'ssafetousebothfunctionsinconditions.
3.1.5Summary
We learned what any() and all() functions can do and how they work. As you can see, these
functions are
an
efficient
tool
that
helps check conditions and
may improve the readability of your
code.
3.1.6Practice
Computerscience>Programminglanguages>P
ython>Basics>Builtins>Anyandall
3.1.6.1O
bjects
Whichobjectscanyouusewiththefunctionsany()andall()?Selectoneormoreoptionsfromthelist:
list
float
integer
NaN
string
37