Pythong Tutorial Openedg1721824408970
Pythong Tutorial Openedg1721824408970
Pythong Tutorial Openedg1721824408970
ISBN: 979-8-9877622-0-2
Cover Design
Konrad Papka
INTRODUCTION
About the course
Syllabus
Prepare for the PCEP-30-0x exam
APPENDICES
APPENDIX A: LAB HINTS
APPENDIX B: LAB SAMPLE SOLUTIONS
APPENDIX C: ANSWERS
APPENDIX D: PCEP EXAM SYLLABUS
WELCOME TO PYTHON ESSENTIALS 1
Learn Python – the language of today and tomorrow
This course is the first in a two-course Python Essentials series.
It covers everything you need to know to start designing,
writing, running, debugging, and improving Python programs
at the foundational level. It also fully prepares you for the PCEP
– Certified Entry-Level Python Programmer certification exam
from the Python Institute.
INTRODUCTION
Python is one of the fastest growing programming languages in
the world, and is used in almost every sector and industry, from
gaming, to medicine, to nuclear physics. It is essential for any
would-be programmer to have at least a foundational
knowledge of Python.
Luckily, Python is also one of the easiest programming
languages to learn. With its focus on real-world words and
syntax, a beginner learner of Python can start writing simple
programs within minutes
Learning Tools
Edube
The material found in this book may also be accessed online at
www.edube.org. Here it is possible to take other courses such as
JavaScript Essentials, or C/C++ Essentials, and progress to the
intermediate and advances Python courses. Furthermore,
through the Edube platform, you can purchase exam vouchers
and schedule an exam.
Sandbox
The Edube educational platform offers an interactive
programming sandbox, where you can try out the code
examples shown in this book. The Sandbox becomes available
as soon as you create an account on Edube.
About the course
Welcome to Python Essentials 1! This course has been designed
and developed by the OpenEDG Python Institute in partnership
with the Cisco Networking Academy.
The course has been created for anyone and everyone who
wants to learn Python and modern programming techniques. It
will particularly appeal to:
Disdvantages
The compilation itself may be a very time-consuming
process – you may not be able to run your code
immediately after making an amendment;
You have to have as many compilers as hardware
platforms you want your code to be run on.
Interpretation
Advantages
You can run the code as soon as you complete it – there are
no additional phases of translation;
The code is stored using programming language, not
machine language – this means that it can be run on
computers using different machine languages; you don’t
compile your code separately for each different
architecture.
Disdvantages
Don’t expect interpretation to ramp up your code to high
speed – your code will share the computer’s power with
the interpreter, so it can’t be really fast;
Both you and the end user have to have the interpreter to
run your code.
Python goals
In 1999, Guido van Rossum defined his goals for Python:
Python rivals
Python has two direct competitors, with comparable properties
and predispositions. These are:
The PyPy logo is a rebus. Can you solve it? It means: a Python
within a Python. In other words, it represents a Python
environment written in Python-like language
named RPython (Restricted Python). It is actually a subset of
Python.
The source code of PyPy is not run in the interpretation
manner, but is instead translated into the C programming
language and then executed separately.
This is useful because if you want to test any new feature that
may be (but doesn’t have to be) introduced into mainstream
Python implementation, it’s easier to check it with PyPy than
with CPython. This is why PyPy is rather a tool for people
developing Python than for the rest of the users.
This doesn’t make PyPy any less important or less serious than
CPython, of course.
In addition, PyPy is compatible with the Python 3 language.
There are many more different Pythons in the world. You’ll find
them if you look, but this course will focus on CPython.
at the shell prompt, press Enter and wait. If you see something
like this:
then you don’t have to do anything else.
If Python 3 is absent, then refer to your Linux documentation in
order to find out how to use your package manager to download
and install a new package – the one you need is
named python3 or its name begins with that.
All non-Linux users can download a copy at
https://www.python.org/downloads/.
Note: don’t set any extension for the file name you are going to
use. Python needs its files to have the .py extension, so you
should rely on the dialog window’s defaults. Using the standard
.py extension enables the OS to properly open these files.
Now put just one line into your newly opened and named editor
window.
The line looks like this:
print(“Hisssssss…”)
You can use the clipboard to copy the text into the file.
We’re not going to explain the meaning of the program right
now. You’ll find a detailed discussion in the next chapter.
Take a closer look at the quotation marks. These are the
simplest form of quotation marks (neutral, straight, dumb, etc.)
commonly used in source files. Do not try to use typographic
quotes (curved, curly, smart, etc.), used by advanced text
processors, as Python doesn’t accept them.
Save the file (File -> Save) and run the program (Run -> Run
Module).
If everything goes okay and there are no mistakes in the code,
the console window will show you the effects caused by
running the program.
In this case, the program hisses.
Try to run it once again. And once more.
Now close both windows now and return to the desktop.
Click File, Open, point to the file you saved previously and
let IDLE read it in.
Try to run it again by pressing F5 when the editor window
is active.
As you can see, IDLE is able to save your code and retrieve it
when you need it again.
IDLE contains one additional and helpful feature.
This is because the nature of the error is different and the error
is discovered at a different stage of interpretation.
The editor window will not provide any useful information
regarding the error, but the console windows might.
The message (in red) shows (in the subsequent lines):
Experiment with creating new files and running your code. Try
to output a different message to the screen, e.g. roar!, meow, or
even maybe an oink!. Try to spoil and fix your code – see what
happens.
MODULE 2: PYTHON DATA TYPES, VARIABLES,
OPERATORS, AND BASIC I/O OPERATIONS
SECTION 2.1 – THE “HELLO, WORLD!” PROGRAM
Welcome to Module two! In the first section, we will learn about
the most essential elements of syntax and semantics of the
Python language, and use them to build your very first Python
program – “Hello, World!”.
2.1.1 Your very first program
It’s time to start writing some real, working Python code. It’ll
be very simple for the time being.
As we’re going to show you some fundamental concepts and
terms, these snippets of code won’t be all that serious or
complex.
Run the following code. If everything goes okay here, you’ll see
the line of text in the console window.
Alternatively, launch IDLE, create a new Python source file, fill
it with this code, name the file and save it. Now run it. If
everything goes okay, you’ll see the text contained within the
quotation marks in the IDLE console window. The code you
have run should look familiar. You saw something very similar
when we led you through the setting up of the IDLE
environment.
1 print(“Hello, world!”)
2
1 print(“Hello, World!”)
2
The word print that you can see here is a function name. That
doesn’t mean that wherever the word appears it is always a
function name. The meaning of the word comes from the
context in which the word has been used.
You’ve probably encountered the term function many times
before, during math classes. You can probably also list several
names of mathematical functions, like sine or log.
Python functions, however, are more flexible, and can contain
more content than their mathematical siblings.
A function (in this context) is a separate part of the computer
code able to:
an effect;
a result.
1 print(“Hello, world!”)
2
We’ll discuss this in more depth soon, but let’s just shed a little
light on it right now.
What happens when Python encounters an invocation like this
one?
function_name(argument)
Let’s see:
Sample Solution
2.1.5 The print() function and its effect, arguments,
and values returned
Three important questions have to be answered as soon as
possible:
1. What effect does the print() function cause?
The effect is very useful and very spectacular. The function:
No wonder then, that from now on, you’ll utilize print() very
intensively to see the results of your operations and
evaluations.
2. What arguments does print() expect?
Any. We’ll show you soon that print() is able to operate with
virtually all types of data offered by Python. Strings, numbers,
characters, logical values, objects ‒ any of these may be
successfully passed to print().
3. What value does the print() function return?
None. Its effect is enough.
2.1.6 Instructions
You have already seen a computer program that contains one
function invocation. A function invocation is one of many
possible kinds of Python instruction.
Of course, any complex program usually contains many more
instructions than one. The question is: how do you couple more
than one instruction into the Python code?
Python’s syntax is quite specific in this area. Unlike most
programming languages, Python requires that there cannot be
more than one instruction in a line.
A line can be empty (i.e. it may contain no instruction at all) but
it must not contain two, three or more instructions. This is
strictly prohibited.
Note: Python makes one exception to this rule ‒ it allows one
instruction to spread across more than one line (which may be
helpful when your code contains complex constructions).
Let’s expand the code a bit. Run it and note what you see.
The spaces, removed from the strings, have appeared again. Can
you explain why?
Two conclusions emerge from this example:
a print() function invoked with more than one
argument outputs them all on one line;
Code
1 print(“Programming”,“Essentials”,“in”)
2 print(“Python”)
3
Sample Solution
LAB 3 Formatting the output
We strongly encourage you to play with the code we’ve written
for you, and make some (maybe even destructive) amendments.
Feel free to modify any part of the code, but there is one
condition ‒ learn from your mistakes and draw your own
conclusions.
Try to:
Code
1 print(” *”)
2 print(” * *”)
3 print(” * *”)
4 print(” * *”)
5 print(“*** ***”)
6 print(” * *”)
7 print(” * *”)
8 print(” *****”)
9
Sample Solution
2.1 SECTION SUMMARY
1. The print() function is a built-in function. It prints/outputs
a specified message to the screen/console window.
2. Built-in functions, contrary to user-defined functions, are
always available and don’t have to be imported. Python 3.8
comes with 69 built-in functions. You can find their full list
provided in alphabetical order in the Python Standard Library.
3. To call a function (this process is known as function
invocation or function call), you need to use the function name
followed by parentheses. You can pass arguments into a
function by placing them inside the parentheses. You must
separate arguments with a comma, e.g. print(“Hello,”,
“world!”). An “empty” print() function outputs an empty
line to the screen.
4. Python strings are delimited with quotes, e.g. “I am a
string” (double quotes), or ‘I am a string, too’ (single
quotes).
5. Computer programs are collections of instructions. An
instruction is a command to perform a specific task when
executed, e.g. to print a certain message to the screen.
6. In Python strings the backslash (\) is a special character
which announces that the next character has a different
meaning, e.g. \n (the newline character) starts a new output
line.
7. Positional arguments are the ones whose meaning is
dictated by their position, e.g. the second argument is
outputted after the first, the third is outputted after the second,
etc.
8. Keyword arguments are the ones whose meaning is not
dictated by their location, but by a special word (keyword) used
to identify them.
9. The end and sep parameters can be used for formatting the
output of the print() function. The sep parameter specifies
the separator between the outputted arguments,
e.g. print(“H”, “E”, “L”, “L”, “O”, sep=”-“), whereas
the end parameter specifies what to print at the end of the print
statement.
2.1 SECTION QUIZ
Question 1: What is the output of the following program?
1 print(“My\nname\nis\nBond.”, end=” “)
2 print(“James Bond.”)
3
Check
SECTION 2.2 – PYTHON LITERALS
Now it’s time to talk about Python literals.
2.2.1 Literals – the data in itself
Now that you have a little knowledge of some of the powerful
features offered by the print() function, it’s time to learn
about some new issues, and one important new term ‒
the literal.
A literal is data whose values are determined by the literal
itself.
As this is a difficult concept to understand, a good example may
be helpful.
Take a look at the following set of digits:
123
1 print(“2”)
2 print(2)
3
1 print(0o123)
2
1 print(0x123)
2
2.2.3 Floats
Now it’s time to talk about another type, which is designed to
represent and to store the numbers that (as a mathematician
would say) have a non-empty decimal fraction.
They are the numbers that have (or may have) a fractional part
after the decimal point, and although such a definition is very
poor, it’s certainly sufficient for what we wish to discuss.
Whenever we use a term like two and a half or minus zero point
four, we think of numbers which the computer
considers floating-point numbers:
2.5
-0.4
You may think that they are exactly the same, but Python sees
them in a completely different way.
4 is an integer number, whereas 4.0 is a floating-
point number.
The point is what makes a float.
On the other hand, it’s not only points that make a float. You
can also use the letter e.
When you want to use any numbers that are very large or very
small, you can use scientific notation.
Take, for example, the speed of light, expressed in meters per
second. Written directly it would look like this: 300000000.
To avoid writing out so many zeros, physics textbooks use an
abbreviated form, which you have probably already seen: 3 x
108.
It reads: three times ten to the power of eight.
In Python, the same effect is achieved in a slightly different way
‒ take a look:
3E8
The letter E (you can also use the lower-case letter e ‒ it comes
from the word exponent) is a concise record of the phrase times
ten to the power of.
Note:
Coding floats
Let’s see how this convention is used to record numbers that are
very small (in the sense of their absolute value, which is close to
zero).
A physical constant called Planck’s constant (and denoted as h),
according to the textbooks, has the value of: 6.62607 x 10-34.
If you would like to use it in a program, you should write it this
way:
6.62607E-34
Note: the fact that you’ve chosen one of the possible forms of
coding float values doesn’t mean that Python will present it the
same way.
Python may sometimes choose different notation than you.
For example, let’s say you’ve decided to use the following float
literal:
0.0000000000000000000001
Note: there are two escaped quotes inside the string ‒ can you
see them both?
The second solution may be a bit surprising. Python can use an
apostrophe instead of a quote. Either of these characters may
delimit strings, but you must be consistent.
If you open a string with a quote, you have to close it with a
quote.
If you start a string with an apostrophe, you have to end it with
an apostrophe.
This example will work too:
Coding strings
Now, the next question is: how do you embed an apostrophe
into a string placed between apostrophes?
You should already know the answer, or to be precise, two
possible answers.
Try to print out a string containing the following message:
I’m Monty Python.
Do you know how to do it? Click Check to see if you were right:
Check (Sample Solutions)
As you can see, the backslash is a very powerful tool ‒ it can
escape not only quotes, but also apostrophes.
We’ve shown it already, but we want to emphasize this
phenomenon once more: a string can be empty ‒ it may
contain no characters at all.
An empty string still remains a string:
”
””
2.2.5 Boolean values
To conclude with Python’s literals, there are two additional
ones.
They’re not as obvious as any of the previous ones, as they’re
used to represent a very abstract value ‒ truthfulness.
Each time you ask Python if one number is greater than
another, the question results in the creation of some specific
data ‒ a Boolean value.
The name comes from George Boole (1815-1864), the author of
the fundamental work, The Laws of Thought, which contains the
definition of Boolean algebra ‒ a part of algebra which makes
use of only two distinct values: True and False, denoted
as 1 and 0.
A programmer writes a program, and the program asks
questions. Python executes the program, and provides the
answers. The program must be able to react according to the
received answers.
Fortunately, computers know only two kinds of answers:
Hint
Sample Solution
2.2 SECTION SUMMARY
1. Literals are notations for representing some fixed values in
code. Python has various types of literals – for example, a literal
can be a number (numeric literals, e.g. 123), or a string (string
literals, e.g. “I am a literal.”).
2. The binary system is a system of numbers that employs 2 as
the base. Therefore, a binary number is made up of 0s and 1s
only, e.g. 1010 is 10 in decimal.
Octal and hexadecimal numeration systems, similarly,
employ 8 and 16 as their bases respectively. The hexadecimal
system uses the decimal numbers and six extra letters.
3. Integers (or simply ints) are one of the numerical types
supported by Python. They are numbers written without a
fractional component, e.g. 256, or -1 (negative integers).
4. Floating-point numbers (or simply floats) are another one of
the numerical types supported by Python. They are numbers
that contain (or are able to contain) a fractional component,
e.g. 1.27.
5. To encode an apostrophe or a quote inside a string, you can
either use the escape character, e.g. ‘I'm happy.’, or open and
close the string using an opposite set of symbols to the ones you
wish to encode, e.g. “I’m happy.” to encode an apostrophe,
and ‘He said “Python”, not “typhoon”’ to encode a
(double) quote.
6. Boolean values are the two constant
objects True and False used to represent truth values (in
numeric contexts 1 is True, while 0 is False.
EXTRA
There is one more, special literal that is used in Python:
the None literal. This literal is a NoneType object, and it is used
to represent the absence of a value. We’ll tell you more about it
soon.
2.2 SECTION QUIZ
Question 1: What types of literals are the following two
examples?
“Hello “, “007”
Check
SECTION 2.3 – OPERATORS: DATA MANIPULATION TOOLS
In this section, we will talk about Python operators.
2.3.1 Python as a calculator
Now, we’re going to show you a completely new side of
the print() function. You already know that the function is
able to show you the values of the literals passed to it by
arguments.
1 print(2+2)
2
Exponentiation
Look at the following example:
1 print(2 ** 3)
2 print(2 ** 3.)
3 print(2. ** 3)
4 print(2. ** 3.)
5
Multiplication
An * (asterisk) sign is a multiplication operator.
Run the following code and check if our integer vs. float rule is
still working.
1 print(2 * 3)
2 print(2 * 3.)
3 print(2. * 3)
4 print(2. * 3.)
5
Division
A / (slash) sign is a division operator.
The value in front of the slash is a dividend, the value behind
the slash, a divisor.
Run the following code and analyze the results.
1 print(6 / 3)
2 print(6 / 3.)
3 print(6. / 3)
4 print(6. / 3.)
5
1 print(6 // 3)
2 print(6 // 3.)
3 print(6. // 3)
4 print(6. // 3.)
5
1 print(6 // 4)
2 print(6. // 4)
3
1 print(-6 // 4)
2 print(6. // -4)
3
Note: some of the values are negative. This will obviously affect
the result. But how?
The result is two negative twos. The real (not rounded) result
is -1.5 in both cases. However, the results are the subjects of
rounding. The rounding goes toward the lesser integer value,
and the lesser integer value is -2, hence: -2 and -2.0.
NOTE
Integer division can also be called floor division. You will
definitely come across this term in the future.
Remainder (modulo)
The next operator is quite a peculiar one, because it has no
equivalent among traditional arithmetic operators.
Its graphical representation in Python is the % (percent) sign,
which may look a bit confusing.
Try to think of it as a slash (division operator) accompanied by
two funny little circles.
The result of the operator is a remainder left after the integer
division.
In other words, it’s the value left over after dividing one value
by another to produce an integer quotient.
Note: the operator is sometimes called modulo in other
programming languages.
Take a look at the snippet ‒ try to predict its result and then run
it:
1 print(14 % 4)
2
1 print(12 % 4.5)
2
Addition
The addition operator is the + (plus) sign, which is fully in line
with mathematical standards.
Again, take a look at the snippet of the following program:
1 print(-4 + 4)
2 print(-4. + 8)
3
By the way: there is also a unary + operator. You can use it like
this:
1 print(+2)
2
The operator preserves the sign of its only argument – the right
one.
Although such a construction is syntactically correct, using it
doesn’t make much sense, and it would be hard to find a good
rationale for doing so.
Take a look at the previous snippet ‒ can you guess its output?
2.3.3 Operators and their priorities
So far, we’ve treated each operator as if it had no connection
with the others. Obviously, such an ideal and simple situation is
a rarity in real programming.
Also, you will very often find more than one operator in one
expression, and then things are no longer so simple.
Consider the following expression:
2 + 3 * 5
1 print(9 % 6 % 2)
2
1 print(9 % 6 % 2)
2
1 print(2 ** 2 ** 3)
2
2 ** 2 → 4; 4 ** 3 → 64
2 ** 3 → 8; 2 ** 8 → 256
Run the code. What do you see?
The result clearly shows that the exponentiation operator uses
right-sided binding.
This has an interesting effect. If the exponentiation operator
uses right-sided binding, can you guess the output of the
following snippet?
1 print(-3 ** 2)
2 print(-2 ** 3)
3 print(-(3 ** 2))
4
Check
List of priorities
Since you’re new to Python operators, we don’t want to present
the complete list of operator priorities right now.
Instead, we’ll show you a truncated form, and we’ll expand it
consistently as we introduce new operators.
Look at the following table:
PRIORITY OPERATOR
1 **
+, – (note: unary operators located next to the
2 right of the power operator bind more unary
strongly)
3 *, /, //, %
4 +, - binary
Note: we’ve enumerated the operators in order from the
highest (1) to the lowest (4) priorities.
Try to work through the following expression:
1 print(2 * 3 % 5)
2
Check
SECTION 2.4 – VARIABLES
This part of the course focuses on variables – we will learn what
they are, how to use them, and what the rules are that govern
them. Ready?
2.4.1 Variables – data-shaped boxes
It seems fairly obvious that Python should allow you to encode
literals carrying number and text values.
You already know that you can do some arithmetic operations
with these numbers: add, subtract, etc. You’ll be doing that
many times.
But it’s quite a normal question to ask how to store the
results of these operations, in order to use them in other
operations, and so on.
How do you save the intermediate results, and use them again
to produce subsequent ones?
Python will help you with that. It offers special “boxes” (or
“containers” as we may call them) for that purpose, and these
boxes are called variables ‒ the name itself suggests that the
content of these containers can be varied in (almost) any way.
What does every Python variable have?
a name;
a value (the content of the container)
MyVariable
i
l
t34
Exchange_Rate
counter
days_to_christmas
TheNameIsTooLongAndHardlyReadable
_
Adiós_Señora
sûr_la_mer
Einbahnstraße
переменная
Python lets you use not only Latin letters but also characters
specific to languages that use other alphabets.
And now for some incorrect names:
NOTE
The PEP 8 — Style Guide for Python Code recommends the
following naming convention for variables and functions in
Python:
variable names should be lowercase, with words
separated by underscores to improve readability
(e.g. var, my_variable)
function names follow the same convention as variable
names (e.g. fun, my_function)
it’s also possible to use mixed case (e.g. myVariable), but
only in contexts where that’s already the prevailing style,
to retain backward compatibility with the adopted
convention.
Keywords
Take a look at the list of words that play a very special role in
every Python program.
[‘False’, ‘None’, ‘True’, ‘and’, ‘as’, ‘assert’,
‘break’, ‘class’, ‘continue’, ‘def’, ‘del’,
‘elif’, ‘else’, ‘except’, ‘finally’, ‘for’,
‘from’, ‘global’, ‘if’, ‘import’, ‘in’, ‘is’,
‘lambda’, ‘nonlocal’, ‘not’, ‘or’, ‘pass’,
‘raise’, ‘return’, ‘try’, ‘while’, ‘with’,
‘yield’]
1 var = 1
2 account_balance = 1000.0
3 client_name = ‘John Doe’
4 print(var, account_balance, client_name)
5 print(var)
6
1 var = 1
2 print(Var)
3
1 var = 1
2 print(var)
3 var = var + 1
4 print(var)
5
1 var = 100
2 var = 200 + 300
3 print(var)
4
Check
2.4.6 Solving simple mathematical problems
Now you should be able to construct a short program solving
simple mathematical problems such as the Pythagorean
theorem:
The square of the hypotenuse is equal to the sum of the squares of
the other two sides.
The following code evaluates the length of the hypotenuse (i.e.
the longest side of a right-angled triangle, the one opposite of
the right angle) using the Pythagorean theorem:
1 a = 3.0
2 b = 4.0
3 c = (a ** 2 + b ** 2) ** 0.5
4 print(“c =”, c)
5
Sample Solution
2.4.7 Shortcut operators
It’s time for the next set of operators that make a developer’s life
easier. Very often, we want to use one and the same variable
both to the right and left sides of the = operator.
For example, if we need to calculate a series of successive values
of powers of 2, we may use a piece like this:
1 x = x * 2
2
You may use an expression like this if you can’t fall asleep and
you’re trying to deal with it using some good, old-fashioned
methods:
1 sheep = sheep + 1
2
1 x *= 2
2 sheep += 1
3
X = X ** 2 x **= 2
LAB 6 Variables ‒ a simple converter
Miles and kilometers are units of length or distance.
Bearing in mind that 1 mile is equal to
approximately 1.61 kilometers, complete the program so that it
converts:
miles to kilometers;
kilometers to miles.
Code
1 kilometers = 12.25
2 miles = 7.38
3 miles_to_kilometers = ###
4 kilometers_to_miles = ###
5 print(miles, “miles
is”, round(miles_to_kilometers, 2), “kilometers”)
6 print(kilometers, “kilometers
is”, round(kilometers_to_miles, 2), “miles”)
7
Sample Solution
LAB 7 Operators and expressions
Take a look at the following code: it reads a float value, puts it
into a variable named x, and prints the value of a variable
named y. Your task is to complete the code in order to evaluate
the following expression:
3x3 – 2x2 + 3x – 1
The result should be assigned to y.
Remember that classical algebraic notation likes to omit the
multiplication operator ‒ you need to use it explicitly. Note how
we change data type to make sure that x is of type float.
Keep your code clean and readable, and test it using the data
we’ve provided, each time assigning it to the x variable (by
hardcoding it). Don’t be discouraged by any initial failures. Be
persistent and inquisitive.
Sample input
x = 0
x = 1
x = -1
Sample output
y = -1.0
y = 3.0
y = -9.0
Code
1 x = # Hardcode your test data here.
2 x = float(x)
3 # Write your code here.
4 print(“y =”, y)
5
Sample Solution
2.4 SECTION SUMMARY
1. A variable is a named location reserved to store values in the
memory. A variable is created or initialized automatically when
you assign a value to it for the first time. (Section 2.4.1)
2. Each variable must have a unique name ‒ an identifier. A
legal identifier name must be a non-empty sequence of
characters, must begin with the underscore(_), or a letter, and it
cannot be a Python keyword. The first character may be
followed by underscores, letters, and digits. Identifiers in
Python are case-sensitive.
3. Python is a dynamically-typed language, which means you
don’t need to declare variables in it. (Section 2.4.3) To assign
values to variables, you can use a simple assignment operator in
the form of the equal (=) sign, i.e. var = 1.
4. You can also use compound assignment operators (shortcut
operators) to modify values assigned to variables, for
example: var += 1, or var /= 5 * 2.
5. You can assign new values to already existing variables using
the assignment operator or one of the compound operators, for
example:
1 var = 2
2 print(var)
3 var = 3
4 print(var)
5 var += 1
6 print(var)
7
6. You can combine text and variables using the + operator, and
use the print() function to output strings and variables, for
example:
1 var = “007”
2 print(“Agent “ + var)
3
2.4 SECTION QUIZ
Question 1: What is the output of the following code?
1 var = 2
2 var = 3
3 print(var)
4
3
2
5
my_var
m
101
averylongVariablename
m101
m 101
Del
del
1
11
2
1 a = 6
2 b = 3
3 a /= 2 * b
4 print(a)
5
1.0
1
9
6
6.0
Check
SECTION 2.5 – COMMENTS
In this section, we want to share with you a few comments on
comments. You will learn here why it is important to document
your code, and why you should leave comments. You will also
learn how to do it, and when comments are considered good
practice. Let’s go!
2.5.1 Comments – why, when, and how?
You may want to put in a few words addressed not to Python
but to humans, usually to explain to other readers of the code
how the tricks used in the code work, or the meanings of the
variables, and eventually, in order to keep stored information
on who the author is and when the program was written.
A remark inserted into the program, which is omitted at
runtime, is called a comment.
How do you leave this kind of comment in the source code? It
has to be done in a way that won’t force Python to interpret it as
part of the code.
Whenever Python encounters a comment in your program, the
comment is completely transparent to it ‒ from Python’s point
of view, this is only one space (regardless of how long the real
comment is).
In Python, a comment is a piece of text that begins with
a # (hash) sign and extends to the end of the line.
If you want a comment that spans several lines, you have to put
a hash in front of them all. Just like here:
1 # uncomment_me = 1
2 # uncomment_me_too = 3
3 # uncomment_me_also = 5
4 print(uncomment_me, uncomment_me_too,
uncomment_me_also, sep=”\n”)
5
LAB 8 Comments
The code contains comments. Try to improve it: add or remove
comments where you find it appropriate (yes, sometimes
removing a comment can make the code more readable), and
change variable names where you think this will improve code
comprehension.
NOTE
Comments are very important. They are used not only to make
your programs easier to understand, but also to disable those
pieces of code that are currently not needed (e.g. when you
need to test some parts of your code only, and ignore others).
Good programmers describe each important piece of code, and
give self-commenting names to variables, as sometimes it is
simply much better to leave information in the code.
It’s good to use readable variable names, and sometimes it’s
better to divide your code into named pieces (e.g. functions). In
some situations, it’s a good idea to write the steps of
computations in a clearer way.
One more thing: it may happen that a comment contains a
wrong or incorrect piece of information ‒ you should never do
that on purpose!
Code
1 #this program computes the number of seconds in a
given number of hours
2 # this program was written two days ago
3 a = 2 # number of hours
4 seconds = 3600 # number of seconds in 1 hour
5 print(“Hours: “, a) #printing the number of hours
6 # print(“Seconds in Hours: “, a * seconds) # printing
the number of seconds in a given number of hours
7 #here we should also print “Goodbye”, but a programmer
didn’t have time to write any code
8 #this is the end of the program that computes the
number of seconds in 3 hours
9
2.5 SECTION SUMMARY
1. Comments can be used to leave additional information in
code. They are omitted at runtime. The information left in the
source code is addressed to human readers. In Python, a
comment is a piece of text that begins with #. The comment
extends to the end of the line.
2. If you want to place a comment that spans several lines, you
need to place # in front of them all. Moreover, you can use a
comment to mark a piece of code that is not needed at the
moment (see the last line of the following snippet), for example:
1 # print(“String #1”)
2 print(“String #2”)
3
1 # This is
2 a multiline
3 comment. #
4 print(“Hello!”)
5
Check
SECTION 2.6 – INTERACTION WITH THE USER
In this section, you will learn how to talk to a computer: you
will familiarize yourself with the input() function, perform
type conversions, and learn how to use string operators.
2.6.1 The input() function
We’re now going to introduce you to a completely new
function, which seems to be a mirror reflection of the good
old print() function.
Why? Well, print() sends data to the console.
The new function gets data from it.
print() has no usable result. The meaning of the new function
is to return a very usable result.
The function is named input(). The name of the function says
everything.
The input() function is able to read data entered by the user
and to return the same data to the running program.
The program can manipulate the data, making the code truly
interactive.
Virtually all programs read and process data. A program which
doesn’t get a user’s input is a deaf program.
Take a look at our example:
1 print(“Tell me anything…”)
2 anything = input()
3 print(“Hmm…”, anything, “… Really?”)
4
Run the code and let the function show you what it can do for
you.
1 print(“Tell me anything…”)
2 anything = input()
3 print(“Hmm…”, anything, “… Really?”)
4
2.6.2 The input() function with an argument
The input() function can do something else: it can prompt the
user without any help from print().
We’ve modified our example a bit, look at the code:
Note:
This is very simple and very effective. Moreover, you can invoke
any of the functions by passing the input() results directly to
them. There’s no need to use any variable as an intermediate
storage.
We’ve implemented the idea ‒ take a look at the code.
Can you imagine how the string entered by the user flows
from input() into print()?
Try to run the modified code. Don’t forget to enter a valid
number.
Check some different values, small and big, negative and
positive. Zero is a good input, too.
1 anything = float(input(“Enter a number: “))
2 something = anything ** 2.0
3 print(anything, “to the power of 2 is”, something)
4
2.6.6 More about input() and type casting
Having a team consisting of the trio input() – int() –
float() opens up lots of new possibilities.
You’ll eventually be able to write complete programs, accepting
data in the form of numbers, processing them and displaying
the results.
Of course, these programs will be very primitive and not very
usable, as they cannot make decisions, and consequently are
not able to react differently to different situations.
This is not really a problem, though; we’ll show you how to
overcome it soon.
Our next example refers to the earlier program to find the
length of a hypotenuse. Let’s run it and make it able to read the
lengths of the legs from the console.
Check out the code ‒ this is what it looks like now:
The program asks the user for the lengths of both legs,
evaluates the hypotenuse and prints the result. Run it and try to
input some negative values.
The program, unfortunately, doesn’t react to this obvious error.
Let’s ignore this weakness for now. We’ll come back to it soon.
Note that in the program that you can see, the hypo variable is
used for only one purpose ‒ to save the calculated value
between the execution of the adjoining line of code.
As the print() function accepts an expression as its argument,
you can remove the variable from the code.
Just like this:
1 string + string
2
Replication
The * (asterisk) sign, when applied to a string and number (or a
number and string, as it remains commutative in this position)
becomes a replication operator:
1 string * number
2 number * string
3
REMEMBER
A number less than or equal to zero produces an empty string.
This simple program “draws” a rectangle, making use of an old
operator (+) in a new role:
Note the way in which we’ve used the parentheses in the second
line of the code.
Try practicing to create other shapes or your own artwork!
2.6.8 Type conversions once again
str()
You already know how to use the int() and float() functions
to convert a string into a number.
This type of conversion is not a one-way street. You can
also convert a number into a string, which is way easier and
safer ‒ this kind of operation is always possible.
A function capable of doing that is called str():
1 str(number)
2
Code
Hint
Sample Solution
LAB 10 Operators and expressions
Your task is to complete the code in order to evaluate the
following expression:
Expected output:
y = 0.6000000000000001
Sample input:
10
Expected output:
y = 0.09901951266867294
Sample input:
100
Expected output:
y = 0.009999000199950014
Sample input:
-5
Expected output:
y = -0.19258202567760344
Code
Sample Solution
LAB 11 Operators and expressions 2
Your task is to prepare a simple code able to evaluate the end
time of a period of time, given as a number of minutes (it could
be arbitrarily large). The start time is given as a pair of hours
(0..23) and minutes (0..59). The result has to be printed to the
console.
For example, if an event starts at 12:17 and lasts 59 minutes, it
will end at 13:16.
Don’t worry about any imperfections in your code ‒ it’s okay if
it accepts an invalid time ‒ the most important thing is that the
code produces valid results for valid input data.
Test your code carefully. Hint: using the % operator may be the
key to success.
Sample input:
12
17
59
Expected output:
13:16
Sample input:
23
58
642
Expected output:
10:40
Sample input:
0
2939
Expected output:
1:0
Code
Hint
Sample Solution
2.6 SECTION SUMMARY
The print() function sends data to the console, while
the input() function gets data from the console.
The input() function comes with an optional parameter: the
prompt string. It allows you to write a message before the user
input, e.g.:
Check
MODULE 3: BOOLEAN VALUES, CONDITIONAL
EXECUTION, LOOPS, LISTS AND LIST PROCESSING,
LOGICAL AND BITWISE OPERATIONS
SECTION 3.1 – MAKING DECISIONS IN PYTHON
Welcome to Module three! In the first section, we will learn
about conditional statements and how to use them to make
decisions in Python.
3.1.1 Questions and answers
A programmer writes a program and the program asks
questions.
A computer executes the program and provides the answers.
The program must be able to react according to the received
answers.
Fortunately, computers know only two kinds of answers:
You will never get a response like Let me think…., I don’t know,
or Probably yes, but I don’t know for sure.
To ask questions, Python uses a set of very special operators.
Let’s go through them one after another, illustrating their
effects on some simple examples.
3.1.2 Comparison: equality operator
Question: are two values equal?
To ask this question, you use the == (equal equal) operator.
Don’t forget this important distinction:
Check
3.1.4 Operators
Equality: the equal to operator (==)
The == (equal to) operator compares the values of two operands.
If they are equal, the result of the comparison is True. If they
are not equal, the result of the comparison is False.
Look at the equality following comparison – what is the result
of this operation?
var == 0
print(var != 0)
print(var != 0)
The content of the variable will tell you the answer to the
question asked.
The second possibility is more convenient and far more
common: you can use the answer you get to make a decision
about the future of the program.
You need a special instruction for this purpose, and we’ll
discuss it very soon.
Now we need to update our priority table, and put all the new
operators into it. It now looks as follows:
PRIORITY OPERATOR
1 +, - unary
2 **
3 *, /, //, %
4 +, - binary
5 <, <=, >, >=
6 ==, !=
LAB 12 Variables ‒ Questions and answers
Using one of the comparison operators in Python, write a
simple two-line program that takes the parameter n as input,
which is an integer, and prints False if n is less than 100,
and True if n is greater than or equal to 100.
Don’t create any if blocks (we’re going to talk about them very
soon). Test your code using the data we’ve provided for you.
Sample input:
55
Expected output:
False
Sample input:
99
Expected output:
False
Sample input:
100
Expected output:
True
Sample input:
101
Expected output:
True
Sample input:
-5
Expected output:
False
Sample input:
+123
Expected output:
True
Sample Solution
3.1.6 Conditions and conditional execution
You already know how to ask Python questions, but you still
don’t know how to make reasonable use of the answers. You
have to have a mechanism which will allow you to do
something if a condition is met, and not do it if it isn’t.
It’s just like in real life: you do certain things or you don’t when
a specific condition is met or not, e.g. you go for a walk if the
weather is good, or stay home if it’s wet and cold.
To make such decisions, Python offers a special instruction. Due
to its nature and its application, it’s called a conditional
instruction (or conditional statement).
There are several variants of it. We’ll start with the simplest,
increasing the difficulty slowly.
The first form of a conditional statement is written very
informally but figuratively:
if true_or_not:
do_this_if_true
the if keyword;
one or more white spaces;
an expression (a question or an answer) whose value will
be interpreted solely in terms of True (when its value is
non-zero) and False (when it is equal to zero);
a colon followed by a newline;
an indented instruction or set of instructions (at least one
instruction is absolutely required); the indentation may
be achieved in two ways – by inserting a particular
number of spaces (the recommendation is to use four
spaces of indentation), or by using the tab character;
note: if there is more than one instruction in the indented
part, the indentation should be the same in all lines; even
though it may look the same if you use tabs mixed with
spaces, it’s important to make all indentations exactly the
same – Python 3 does not allow the mixing of spaces and
tabs for indentation.
1 if the_weather_is_good:
2 go_for_a_walk()
3 have_lunch()
4
As you can see, making a bed, taking a shower and falling asleep
and dreaming are all executed conditionally –
when sheep_counter reaches the desired limit.
Feeding the sheepdogs, however, is always done (i.e.
the feed_the_sheepdogs() function is not indented and does
not belong to the if block, which means it is always executed.)
Now we’re going to discuss another variant of the conditional
statement, which also allows you to perform an additional
action when the condition is not met.
1 if true_or_false_condition:
2 perform_if_condition_true
3 else:
4 perform_if_condition_false
5
1 if the_weather_is_good:
2 go_for_a_walk()
3 have_fun()
4 else:
5 go_to_a_theater()
6 enjoy_the_movie()
7 have_lunch()
8
1 if the_weather_is_good:
2 if nice_restaurant_is_found:
3 have_lunch()
4 else:
5 eat_a_sandwich()
6 else:
7 if tickets_are_available:
8 go_to_the_theater()
9 else:
10 go_shopping()
11
1 if the_weather_is_good:
2 go_for_a_walk()
3 elif tickets_are_available:
4 go_to_the_theater()
5 elif table_is_available:
6 go_for_lunch()
7 else:
8 play_chess_at_home()
9
By the same fashion, you can use the min() function to return
the lowest number. You can rebuild this code and experiment
with it in the Sandbox.
We’re going to talk about these (and many other) functions
soon. For the time being, our focus will be on conditional
execution and loops to let you gain more confidence in
programming and teach you the skills that will let you fully
understand and apply the two concepts in your code. So, for
now, we’re not taking any shortcuts.
LAB 13 Comparison operators and conditional execution
Spathiphyllum, more commonly known as a peace lily or white
sail plant, is one of the most popular indoor houseplants that
filters out harmful toxins from the air. Some of the toxins that it
neutralizes include benzene, formaldehyde, and ammonia.
Imagine that your computer program loves these plants.
Whenever it receives an input in the form of the
word Spathiphyllum, it involuntarily shouts to the console the
following string: “Spathiphyllum is the best plant
ever!”
Write a program that utilizes the concept of conditional
execution, takes a string as input, and:
Test your code using the data we’ve provided for you. And get
yourself a Spathiphyllum, too!
Sample input:
spathiphyllum
Expected output:
No, I want a big Spathiphyllum!
Sample input:
pelargonium
Expected output:
Spathiphyllum! Not pelargonium!
Sample input:
Spathiphyllum
Expected output:
Yes – Spathiphyllum is the best plant ever!
Sample Solution
LAB 14 Essentials of the if-else statement
Once upon a time there was a land – a land of milk and honey,
inhabited by happy and prosperous people. The people paid
taxes, of course – their happiness had limits. The most
important tax, called the Personal Income Tax (PIT for short) had
to be paid once a year, and was evaluated using the following
rule:
Expected output:
The tax is: 1244.0 thalers
Sample input:
100000
Expected output:
The tax is: 19470.0 thalers
Sample input:
1000
Expected output:
The tax is: 0.0 thalers
Sample input:
-100
Expected output:
The tax is: 0.0 thalers
Code
1 income = float(input(“Enter the annual income: “))
2 if income < 85528:
3 tax = income * 0.18 – 556.02
4 # Write the rest of your code here.
5 tax = round(tax, 0)
6 print(“The tax is:”, tax, “thalers”)
7
Sample Solution
LAB 15 Essentials of the if-elif-else statement
As you surely know, due to some astronomical reasons, years
may be leap or common. The former are 366 days long, while the
latter are 365 days long.
Since the introduction of the Gregorian calendar (in 1582), the
following rule is used to determine the kind of year:
Expected output:
Leap year
Sample input:
2015
Expected output:
Common year
Sample input:
1999
Expected output:
Common year
Sample input:
1996
Expected output:
Leap year
Sample input:
1580
Expected output:
Not within the Gregorian calendar period
Code
1 year = int(input(“Enter a year: “))
2 if year < 1582:
3 print(“Not within the Gregorian calendar period”)
4 else:
5 # Write the if-elif-elif-else block here.
6
Sample Solution
3.1 SECTION SUMMARY
1. The comparison (otherwise known as relational) operators
are used to compare values. The following table illustrates how
the comparison operators work, assuming that x = 0, y = 1,
and z = 0:
x < y #
True if the left operand’s value is less
True
< than the right operand’s value,
y < z #
and False otherwise
False
>= True if the left operand’s value is greater x >= y #
than or equal to the right operand’s False
value, and False otherwise
x >= z #
True
y >= z #
True
x <= y #
True
True if the left operand’s value is less
x <= z #
<= than or equal to the right operand’s
True
value, and False otherwise
y <= z #
False
2. When you want to execute some code only if a certain
condition is met, you can use a conditional statement:
a single if statement, e.g.:
1 x = 10
2 if x == 10: # condition
3 print(“x is equal to 10”) # Executed if the
condition is True.
4
1 x = 10
2 if x < 10: # condition
3 print(“x is less than 10”) # Executed if the
condition is True.
4 else:
5 print(“x is greater than or equal to 10”) #
Executed if the condition is False.
6
1 x = 10
2 if x == 10: # True
3 print(“x == 10”)
4 if x > 15: # False
5 print(“x > 15”)
6 elif x > 10: # False
7 print(“x > 10”)
8 elif x > 5: # True
9 print(“x > 5”)
10 else:
11 print(“else will not be executed”)
12
1 x = 10
2 if x > 5: # True
3 if x == 6: # False
4 print(“nested: x == 6”)
5 elif x == 10: # True
6 print(“nested: x == 10”)
7 else:
8 print(“nested: else”)
9 else:
10 print(“else”)
11
3.1 SECTION QUIZ
Question 1: What is the output of the following snippet?
x = 5
y = 10
z = 8
print(x > y)
print(y > z)
print(x > z)
print((y – 5) == x)
x, y, z = z, y, x
print(x > z)
print((y – 5) == x)
if x == 10:
print(x == 10)
if x > 5:
print(x > 5)
if x < 10:
else:
print(“else”)
if x == 1:
print(“one”)
elif x == “1”:
if int(x) > 1:
print(“two”)
print(“three”)
else:
print(“four”)
if int(x) == 1:
print(“five”)
else:
print(“six”)
y = 1.0
z = “1”
if x == y:
print(“one”)
if y == int(z):
print(“two”)
elif x == y:
print(“three”)
else:
print(“four”)
Check
SECTION 3.2 – LOOPS IN PYTHON
Here you will learn about loops in Python, and specifically –
the while and for loops. You will learn how to create (and
avoid falling into) infinite loops, how to exit loops, and skip
particular loop iterations. Ready?
3.2.1 Looping your code with while
Do you agree with the following statement?
while there is something to do
do it
Note that this record also declares that if there is nothing to do,
nothing at all will happen.
In general, in Python, a loop can be represented as follows:
while
instruction
instruction_one
instruction_two
instruction_three
:
instruction_n
1 while True:
2 print(“I’m stuck inside a loop.”)
3
1 counter = 5
2 while counter != 0:
3 print(“Inside the loop.”, counter)
4 counter -= 1
5 print(“Outside the loop.”, counter)
6
1 counter = 5
2 while counter:
3 print(“Inside the loop.”, counter)
4 counter -= 1
5 print(“Outside the loop.”, counter)
6
Is it more compact than previously? A bit. Is it more legible?
That’s disputable.
REMEMBER
Don’t feel obliged to code your programs in a way that is always
the shortest and the most compact. Readability may be a more
important factor. Keep your code ready for a new programmer.
LAB 16 Guess the secret number
A junior magician has picked a secret number. He has hidden it
in a variable named secret_number. He wants everyone who
runs his program to play the Guess the secret number game, and
guess what number he has picked for them. Those who don’t
guess the number will be stuck in an endless loop forever!
Unfortunately, he does not know how to complete the code.
Your task is to help the magician complete the code in such a
way so that the code:
Code
1 secret_number = 777
2 print(
3 ”””
4 +================================+
5 | Welcome to my game, muggle! |
6 | Enter an integer number |
7 | and guess what number I’ve |
8 | picked for you. |
9 | So, what is the secret number? |
10 +================================+
11 ”””)
12
Hint
Sample Solution
3.2.4 Looping your code with for
Another kind of loop available in Python comes from the
observation that sometimes it’s more important to count the
“turns” of the loop than to check the conditions.
Imagine that a loop’s body needs to be executed exactly one
hundred times. If you would like to use the while loop to do it,
it may look like this:
1 i = 0
2 while i < 100:
3 # do_something()
4 i += 1
5
1 for i in range(100):
2 # do_something()
3 pass
4
There are some new elements. Let us tell you about them:
the for keyword opens the for loop; note – there’s no
condition after it; you don’t have to think about
conditions, as they’re checked internally, without any
intervention;
any variable after the for keyword is the control
variable of the loop; it counts the loop’s turns, and does it
automatically;
the in keyword introduces a syntax element describing
the range of possible values being assigned to the control
variable;
the range() function (this is a very special function) is
responsible for generating all the desired values of the
control variable; in our example, the function will create
(we can even say that it will feed the loop with)
subsequent values from the following set: 0, 1, 2 .. 97, 98,
99; note: in this case, the range() function starts its job
from 0 and finishes it one step (one integer number)
before the value of its argument;
note the pass keyword inside the loop body – it does
nothing at all; it’s an empty instruction – we put it here
because the for loop’s syntax demands at least one
instruction inside the body (by the way –
if, elif, else and while express the same thing)