Cours PythonEssentials Py InstituteM1-2
Cours PythonEssentials Py InstituteM1-2
Python Essentials 1
LIST OF CONTENTS
Welcome to PE1
o BACK
o WELCOME TO PE1
o About the course
BACK
ABOUT THE COURSE
About PE1
Syllabus | Whylearn Python?
Applications for Python
Module 1: Introduction to Python and computer programming
o BACK
o MODULE 1: INTRODUCTION TO PYTHON AND COMPUTER PROGRAMMING
o 1.1. Introduction to programmingwith Python
BACK
1.1. INTRODUCTION TO PROGRAMMING WITH PYTHON
Python Essentials 1 - Module 1
1.1.1.1 Programming - absolute basics
1.1.1.2 Programming - absolute basics
1.1.1.3 Programming - absolute basics
1.1.1.4 Programming - absolute basics | Compilation vs. interpretation
1.1.1.5 Programming - absolute basics | Compilation vs. interpretation
1.1.1.6 Programming - absolute basics | Compilation vs. interpretation
1.1.2.1 Python - a tool, not a reptile
1.1.2.2 Python - a tool, not a reptile
1.1.2.3 Python - a tool, not a reptile | Why Python?
1.1.2.4 Python - a tool, not a reptile | Why Python, why not?
1.1.3.1 Python 2 vs. Python 3
1.1.3.2 There is more than one Python: CPython and Cython
1.1.3.3 There is more than one Python: Jython, PyPy, and RPython
o 1.2. Downloading and installing Python
BACK
TECHNOLOGIES DE L’INFORMATION/ ISET SOUSSE / COURSE OF PYTHON INSTITUTE PAGE 1 SUR 299
1.2. DOWNLOADING AND INSTALLING PYTHON
1.2.1.1 Begin your Python journey
1.2.1.2 Begin your Python journey | Downloading and installing Python
1.2.1.3 Begin your Python journey
1.2.1.4 Begin your Python journey
1.2.1.5 Begin your Python journey
1.2.1.6 Begin your Python journey
1.2.1.7 Begin your Python journey
1.2.1.8 Begin your Python journey
1.2.1.9 Module Completion
o Module 1 Quiz Quiz
BACK
MODULE 1 QUIZ
PE1 -- Module 1 Quiz Quiz
o Module 1 Test Test
BACK
MODULE 1 TEST
PE1 -- Module 1 Test Test
Module 2: Data types, variables, basic I/O operations, and basic operators
o BACK
o MODULE 2: DATA TYPES, VARIABLES, BASIC I/O OPERATIONS, AND BASIC OPERATORS
o 2.1. Hello, world!
BACK
2.1. HELLO, WORLD!
Python Essentials 1: Module 2
2.1.1.1 Yourvery first program
2.1.1.2 Your first program
2.1.1.3 Your first program
2.1.1.4 Your first program
2.1.1.5 Your first program
2.1.1.6 LAB: The print() function Lab
2.1.1.7 Your first program
2.1.1.8 Yourvery first program
2.1.1.9 Yourvery first program
2.1.1.10 Yourvery first program
2.1.1.11 Yourvery first program
2.1.1.12 Yourvery first program
2.1.1.13 Yourvery first program
TECHNOLOGIES DE L’INFORMATION/ ISET SOUSSE / COURSE OF PYTHON INSTITUTE PAGE 2 SUR 299
2.1.1.14 Yourvery first program
2.1.1.15 Yourvery first program
2.1.1.16 Yourvery first program
2.1.1.17 Yourvery first program
2.1.1.18 LAB: The print() function Lab
2.1.1.19 LAB: Formatting the output Lab
2.1.1.20 SECTION SUMMARY
o 2.2. Python literals
BACK
2.2. PYTHON LITERALS
2.2.1.1 Python literals
2.2.1.2 Python literals
2.2.1.3 Python literals
2.2.1.4 Python literals
2.2.1.5 Python literals
2.2.1.6 Python literals
2.2.1.7 Python literals
2.2.1.8 Python literals
2.2.1.9 Python literals
2.2.1.10 Python literals
2.2.1.11 LAB: Python literals - strings Lab
2.2.1.12 SECTION SUMMARY
o 2.3. Arithmetic operators and the hierarchy of priorities
BACK
2.3. ARITHMETIC OPERATORS AND THE HIERARCHY OF PRIORITIES
2.3.1.1 Operators - data manipulation tools
2.3.1.2 Operators - data manipulation tools
2.3.1.3 Operators - data manipulation tools
2.3.1.4 Operators - data manipulation tools
2.3.1.5 Operators - data manipulation tools
2.3.1.6 Operators - data manipulation tools
2.3.1.7 Operators - data manipulation tools
2.3.1.8 Operators - data manipulation tools
2.3.1.9 Operators ‒ data manipulation tools
2.3.1.10 SECTION SUMMARY
o 2.4. Variables
BACK
2.4. VARIABLES
2.4.1.1 Variables - data-shaped boxes
TECHNOLOGIES DE L’INFORMATION/ ISET SOUSSE / COURSE OF PYTHON INSTITUTE PAGE 3 SUR 299
2.4.1.2 Variables - data-shaped boxes
2.4.1.3 Variables - data-shaped boxes
2.4.1.4 Variables - data-shaped boxes
2.4.1.5 Variables - data-shaped boxes
2.4.1.6 Variables - data-shaped boxes
2.4.1.7 LAB: Variables Lab
2.4.1.8 Variables - data-shaped boxes
2.4.1.9 LAB: Variables: a simple converter Lab
2.4.1.10 LAB: Operators and expressions Lab
2.4.1.11 SECTION SUMMARY
o 2.5. Comments
BACK
2.5. COMMENTS
2.5.1.1 A comment on comments
2.5.1.2 LAB: Comments Lab
2.5.1.3 SECTION SUMMARY
o 2.6. The input() function and string operators
BACK
2.6. THE INPUT() FUNCTION AND STRING OPERATORS
2.6.1.1 How to talk to a computer
2.6.1.2 How to talk to a computer
2.6.1.3 How to talk to a computer
2.6.1.4 How to talk to a computer
2.6.1.5 How to talk to a computer
2.6.1.6 How to talk to a computer: string operators
2.6.1.7 How to talk to a computer: string operators
2.6.1.8 How to talk to a computer: string operators
2.6.1.9 LAB: Simple input and output Lab
2.6.1.10 LAB: Operators and expressions Lab
2.6.1.11 LAB: Operators and expressions Lab
2.6.1.12 SECTION SUMMARY
2.6.1.13 Module Completion
o Module 2 Quiz Quiz
BACK
MODULE 2 QUIZ
PE1 -- Module 2 Quiz Quiz
o Module 2 Test Test
BACK
TECHNOLOGIES DE L’INFORMATION/ ISET SOUSSE / COURSE OF PYTHON INSTITUTE PAGE 4 SUR 299
MODULE 2 TEST
PE1 -- Module 2 Test Test
Module 3: Boolean values, conditional execution, loops, lists and list processing, logical
and bitwise operations
o BACK
o MODULE 3: BOOLEAN VALUES, CONDITIONAL EXECUTION, LOOPS, LISTS AND LIST PROCESSING, LOGICAL AND BITWISE OPERATIONS
o 3.1. Comparisonoperators and conditionalexecution
BACK
3.1. COMPARISON OPERATORS AND CONDITIONAL EXECUTION
Python Essentials 1: Module 3
3.1.1.1 Makingdecisions in Python
3.1.1.2 Makingdecisions in Python
3.1.1.3 Makingdecisions in Python
3.1.1.4 LAB: Questions and answers Lab
3.1.1.5 Makingdecisions in Python
3.1.1.6 Makingdecisions in Python
3.1.1.7 Makingdecisions in Python
3.1.1.8 Makingdecisions in Python
3.1.1.9 Makingdecisions in Python
3.1.1.10 LAB: Comparison operators and conditional execution Lab
3.1.1.11 LAB: Essentials of the if-else statement Lab
3.1.1.12 LAB: Essentials of the if-elif-else statement Lab
3.1.1.13 SECTION SUMMARY (1/2)
3.1.1.14 SECTION SUMMARY (2/2)
o 3.2. Loops
BACK
3.2. LOOPS
3.2.1.1 Loops in Python | while
3.2.1.2 Loops in Python | while
3.2.1.3 LAB: Essentials of the while loop - Guess the secret number Lab
3.2.1.4 Loops in Python | for
3.2.1.5 Loops in Python | for
3.2.1.6 LAB: Essentials of the for loop - counting mississippily Lab
3.2.1.7 Loop control in Python | break and continue
3.2.1.8 Loop control in Python | break and continue
3.2.1.9 LAB: The break statement - Stuck in a loop Lab
3.2.1.10 LAB: The continue statement - the Ugly Vowel Eater Lab
TECHNOLOGIES DE L’INFORMATION/ ISET SOUSSE / COURSE OF PYTHON INSTITUTE PAGE 5 SUR 299
3.2.1.11 LAB: The continue statement - the Pretty Vowel Eater Lab
3.2.1.12 Python loops | else
3.2.1.13 Python loops | else
3.2.1.14 LAB: Essentials of the while loop Lab
3.2.1.15 LAB: Collatz'shypothesis Lab
3.2.1.16 SECTION SUMMARY (1/2)
3.2.1.17 SECTION SUMMARY (2/2)
o 3.3. Logic and bit operations in Python
BACK
3.3. LOGIC AND BIT OPERATIONS IN PYTHON
3.3.1.1 Logic and bit operations in Python | and, or, not
3.3.1.2 Logic and bit operations in Python | and, or, not
3.3.1.3 Logic and bit operations in Python
3.3.1.4 Logic and bit operations in Python | Bitwise operators
3.3.1.5 Logic and bit operations in Python | Bit shifting
3.3.1.6 SECTION SUMMARY
o 3.4. Lists
BACK
3.4. LISTS
3.4.1.1 Lists - collections of data
3.4.1.2 Lists - collections of data | Indexing
3.4.1.3 Lists - collections of data | Indexing
3.4.1.4 Lists - collections of data | Operations on lists
3.4.1.5 Lists - collections of data | Operations on lists
3.4.1.6 LAB: The basics of lists Lab
3.4.1.7 Lists - collections of data | Functions and methods
3.4.1.8 Lists - collections of data | list methods
3.4.1.9 Lists - collections of data | list methods
3.4.1.10 Lists - collections of data | lists and loops
3.4.1.11 Lists - collections of data | lists and loops
3.4.1.12 Lists - collections of data | lists and loops
3.4.1.13 LAB: The basics of lists - the Beatles Lab
3.4.1.14 SECTION SUMMARY
o 3.5. Sorting simple lists
BACK
3.5. SORTING SIMPLE LISTS
3.5.1.1 Sorting simple lists - the bubble sort algorithm
3.5.1.2 Sorting simple lists - the bubble sort algorithm
TECHNOLOGIES DE L’INFORMATION/ ISET SOUSSE / COURSE OF PYTHON INSTITUTE PAGE 6 SUR 299
3.5.1.3 Sorting simple lists - the bubble sort algorithm
3.5.1.4 SECTION SUMMARY
o 3.6. List processing
BACK
3.6. LIST PROCESSING
3.6.1.1 Operations on lists
3.6.1.2 Operations on lists | slices
3.6.1.3 Operations on lists | slices
3.6.1.4 Operations on lists | slices
3.6.1.5 Operations on lists | slices, del
3.6.1.6 Operations on lists | in, not in
3.6.1.7 Lists - more details
3.6.1.8 Lists - more details
3.6.1.9 LAB: Operating with lists - basics Lab
3.6.1.10 SECTION SUMMARY
o 3.7.1 Multidimensionalarrays
BACK
3.7.1 MULTIDIMENSIONAL ARRAYS
3.7.1.1 Lists in advanced applications
3.7.1.2 Lists in advanced applications | Arrays
3.7.1.3 Lists in advanced applications | Arrays
3.7.1.4 Lists in advanced applications | Arrays
3.7.1.5 Lists in advanced applications | Arrays
3.7.1.6 SECTION SUMMARY
3.7.1.7 Module Completion
o Module 3 Quiz Quiz
BACK
MODULE 3 QUIZ
PE1 -- Module 3 Quiz Quiz
o Module 3 Test Test
BACK
MODULE 3 TEST
PE1 -- Module 3 Test Test
Module 4: Functions, tuples, dictionaries, and data processing
o BACK
o MODULE 4: FUNCTIONS, TUPLES, DICTIONARIES, AND DATA PROCESSING
o 4.1. Functions
BACK
TECHNOLOGIES DE L’INFORMATION/ ISET SOUSSE / COURSE OF PYTHON INSTITUTE PAGE 7 SUR 299
4.1. FUNCTIONS
Python Essentials 1: Module 4
4.1.1.1 Functions
4.1.1.2 Functions
4.1.1.3 Writingfunctions
4.1.1.4 Writingfunctions
4.1.1.5 Functions
4.1.1.6 SECTION SUMMARY
o 4.2. Functionparameters and argument passing
BACK
4.2. FUNCTION PARAMETERS AND ARGUMENT PASSING
4.2.1.1 How functions communicate with their environment
4.2.1.2 How functions communicate with their environment
4.2.1.3 How functions communicate with their environment
4.2.1.4 How functions communicate with their environment
4.2.1.5 How functions communicate with their environment
4.2.1.6 How functions communicate with their environment
4.2.1.7 How functions communicate with their environment
4.2.1.8 SECTION SUMMARY
o 4.3. Returningresultsfromfunctions
BACK
4.3. RETURNING RESULTS FROM FUNCTIONS
4.3.1.1 Returning a result from a function
4.3.1.2 Returning a result from a function
4.3.1.3 Returning a result from a function
4.3.1.4 Returning a result from a function
4.3.1.5 Returning a result from a function
4.3.1.6 LAB: A leap year: writing your own functions Lab
4.3.1.7 LAB: How many days: writing and using your own functions Lab
4.3.1.8 LAB: Day of the year: writing and using your own functions Lab
4.3.1.9 LAB: Prime numbers - how to find them Lab
4.3.1.10 LAB: Converting fuel consumption Lab
4.3.1.11 SECTION SUMMARY
o 4.4. Functions and scopes
BACK
4.4. FUNCTIONS AND SCOPES
4.4.1.1 Scopes in Python
4.4.1.2 Scopes in Python
TECHNOLOGIES DE L’INFORMATION/ ISET SOUSSE / COURSE OF PYTHON INSTITUTE PAGE 8 SUR 299
4.4.1.3 Scopes in Python | global
4.4.1.4 Scopes in Python
4.4.1.5 SECTION SUMMARY
o 4.5. Creating simple functions
BACK
4.5. CREATING SIMPLE FUNCTIONS
4.5.1.1 Creatingfunctions | two-parameterfunctions
4.5.1.2 Creatingfunctions | two-parameterfunctions
4.5.1.3 Creatingfunctions | three-parameterfunctions
4.5.1.4 Creatingfunctions | testing triangles
4.5.1.5 Creatingfunctions | right-angle triangles
4.5.1.6 Creatingfunctions | factorials
4.5.1.7 Creatingfunctions | Fibonaccinumbers
4.5.1.8 Creatingfunctions | recursion
4.5.1.9 SECTION SUMMARY
o 4.6. Tuples and dictionaries
BACK
4.6. TUPLES AND DICTIONARIES
4.6.1.1 Tuples and dictionaries
4.6.1.2 Tuples and dictionaries
4.6.1.3 Tuples and dictionaries
4.6.1.4 Tuples and dictionaries
4.6.1.5 Tuples and dictionaries
4.6.1.6 Tuples and dictionaries | methods
4.6.1.7 Tuples and dictionaries | methods
4.6.1.8 Tuples and dictionaries
4.6.1.9 Tuples and dictionaries
4.6.1.10 SECTION SUMMARY (1/3)
4.6.1.11 SECTION SUMMARY (2/3)
4.6.1.12 SECTION SUMMARY (3/3)
o 4.7.1 Exceptions
BACK
4.7.1 EXCEPTIONS
4.7.1.1 Exceptions
4.7.1.2 Exceptions
4.7.1.3 Exceptions (try-except)
4.7.1.4 Exceptions
4.7.1.5 Exceptions (two exceptions)
4.7.1.6 Exceptions | Deafult exceptions
TECHNOLOGIES DE L’INFORMATION/ ISET SOUSSE / COURSE OF PYTHON INSTITUTE PAGE 9 SUR 299
4.7.1.7 Exceptions
4.7.1.8 Testing and debugging
4.7.1.9 Testing and debugging
4.7.1.10 Testing: bug vs. debug
4.7.1.11 printdebugging
4.7.1.12 Testing and debugging – tips
4.7.1.13 SECTION SUMMARY
4.7.2.1 PROJECT: Tic-Tac-Toe Lab
4.7.2.2 Module Completion
o Module 4 Quiz Quiz
BACK
MODULE 4 QUIZ
PE1 -- Module 4 Quiz Quiz
o Module 4 Test Test
BACK
MODULE 4 TEST
PE1 -- Module 4 Test Test
Course completion
TECHNOLOGIES DE L’INFORMATION/ ISET SOUSSE / COURSE OF PYTHON INSTITUTE PAGE 10 SUR 299
Module 1
Python Essentials 1
Introduction to Python and Computer Programming
Unfortunately, this tongue is a far cry from a human mother tongue. We all (both computers and humans) need something else, a common language for
computers and humans, or a bridge between the two different worlds.
We need a language in which humans can write their programs and a language that computers may use to execute the programs, one that is far more complex
than machine language and yet far simpler than natural language.
Such languages are often called high-level programming languages. They are at least somewhat similar to natural ones in that they use symbols, words and
conventions readable to humans. These languages enable humans to express commands to computers that are much more complex than those offered by ILs.
A program written in a high-level programming language is called a source code (in contrast to the machine code executed by computers). Similarly, the file
containing the source code is called the source file.
There are two different ways of transforming a program from a high-level programming language into machine language:
COMPILATION - the source program is translated once (however, this act must be repeated each time you modify the source code) by getting a file (e.g., an
.exe file if the code is intended to be run under MS Windows) containing the machine code; now you can distribute the file worldwide; the program that
performs this translation is called a compiler or translator;
INTERPRETATION - you (or any user of the code) can translate the source program each time it has to be run; the program performing this kind of
transformation is called an interpreter, as it interprets the code every time it is intended to be executed; it also means that you cannot just distribute the source
code as-is, because the end-user also needs the interpreter to execute it.
Due to some very fundamental reasons, a particular high-level programming language is designed to fall into one of these two categories.
There are very few languages that can be both compiled and interpreted. Usually, a programming language is projected with this factor in its constructors'
minds - will it be compiled or interpreted?
TECHNOLOGIES DE L’INFORMATION/ ISET SOUSSE / COURSE OF PYTHON INSTITUTE PAGE 12 SUR 299
For example, if you try to use an entity of an unknown name, it will cause an error, but the error will be discovered in the place where it tries to use the entity,
not where the new entity's name was introduced.
In other words, the actual reason is usually located a little earlier in the code, for example, in the place
If the line looks good, the interpreter tries to execute it (note: each line is usually executed separately, so the trio "read-check-execute" can be repeated many
times - more times than the actual number of lines in the source file, as some parts of the code may be executed more than once).
It is also possible that a significant part of the code may be executed successfully before the interpreter finds an error. This is normal behavior in this execution
model.
You may ask now: which is better? The "compiling" model or the "interpreting" model? There is no obvious answer. If there had been, one of these models
would have ceased to exist a long time ago.Both of them have their advantages and their disadvantages.
COMPILATION INTERPRETATION
the execution of the translated code is usually faster; you can run the code as soon as you complete it - there are no additional
only the user has to have the compiler - the end-user may use phases of translation;
the code without it; the code is stored using programming language, not the machine one -
ADVANTAGES
the translated code is stored using machine language - as it is this means that it can be run on computers using different machine
very hard to understand it, your own inventions and languages; you don't compile your code separately for each different
programming tricks are likely to remain your secret. architecture.
TECHNOLOGIES DE L’INFORMATION/ ISET SOUSSE / COURSE OF PYTHON INSTITUTE PAGE 13 SUR 299
Python is an interpreted language. This means that it inherits all the described advantages and disadvantages. Of course, it adds some of its unique features to
both sets.
If you want to program in Python, you'll need the Python interpreter. You won't be able to run your code without it. Fortunately, Python is free. This is
one of its most important advantages.
Due to historical reasons, languages designed to be utilized in the interpretation manner are often called scripting languages, while the source programs
encoded using them are called scripts.
WHAT IS PYTHON?
Python is a widely-used, interpreted, object-oriented, and high-level programming language with dynamic semantics, used for general-purpose programming.
The circumstances in which Python was created are a bit puzzling. According to Guido van Rossum:
In December 1989, I was looking for a "hobby" programming project that would keep me occupied during the week around Christmas. My office (...) would
be closed, but I had a home computer, and not much else on my hands. I decided to write an interpreter for the new scripting language I had been thinking
about lately: a descendant of ABC that would appeal to Unix/C hackers. I chose Python as a working title for the project, being in a slightly irreverent mood
(and a big fan of Monty Python's Flying Circus).Guido van Rossum
PYTHON GOALS
In 1999, Guido van Rossum defined his goals for Python:
an easy and intuitive language just as powerful as those of the major competitors;
open source, so anyone can contribute to its development;
code that is as understandable as plain English;
suitable for everyday tasks, allowing for short development times.
TECHNOLOGIES DE L’INFORMATION/ ISET SOUSSE / COURSE OF PYTHON INSTITUTE PAGE 14 SUR 299
About 200 years later, it is clear that all these intentionss have been fulffilled. Some souurces say that Pyython is the mosst popular progrramming langua
age in the
world, while
w others claimm it's the secondd or the third.
Either way,
w it still occcupies a high rrank in the top p ten of the PY YPL PopulariitY of Progra amming Langu uage and the T TIOBE Progra amming
Commu unity Index. (vvoirhttps://www w.tiobe.com/tiob be-index/)
Python isn't
i a young lan nguage anymoree. It is mature anda trustworthy.. It's not a one-h
hit wonder. It's a bright star in
n the programmiing firmament, and time
spent lea
arning Python iss a very good invvestment.
Pytho
on rivals?
Python has
h two direct com
mpetitors, with co
omparable prope
erties and predisp
positions. These are:
Perl
P - a scripting language origina ally authored by Larry
L Wall;
Ruby
R - a scripting
g language origin
nally authored by Yukihiro Matsum
moto.
The form
mer is more traditiional, more conse
ervative than Pytthon, and resemb
bles some of the good old langua
ages derived from
m the classic C prrogramming lang
guage.
In contra
ast, the latter is more
m innovative and more full of fre
esh ideas than Python.
P Python its
self lies somewhe
ere between thes
se two creations.
Why not
n Python
n? Python’’s weeknes
sses
Despite Python's
P growing
g popularity, there
e are still some niches
n where Python is absent, orr is rarely seen:
lo
ow-level programming (sometimmes called "close e to metal" progra amming): if you want
w to implemen
nt an extremely efffective driver or graphical engine
e, you
wouldn't
w use Pyth
hon;
applications
a for mobile devices: although this te
erritory is still waitting to be conque
ered by Python, it will most likely happen somedayy.
Varietties of Python
Pytho
on aka CPy
ython
TECHNOL
LOGIES DE L’INFO
ORMATION/ ISET
T SOUSSE / COUR
RSE OF PYTHON INSTITUTE
N PAGE 15 SUR 299
9
In additio
on to Python 2 an
nd Python 3, therre is more than one version of eac
ch.
First of all,
a there are the Pythons
P which arre maintained by the people gathe
ered around the PSF (Python Sofftware Foundatioon), a community that aims to dev velop,
improve, expand, and pop pularize Python aand its environme
ent. The PSF's president
p is Guido
o von Rossum himself, and for this reason, these Pythons are
called caanonical. They are also considereed to be referenc
ce Pythons, as any
a other implem mentation of the la
anguage should follow all standarrds established by
b the
PSF.
Guido vaan Rossum used the "C" programming language to o implement the very first version of his language and this decision n is still in force. A
All Pythons comiing from
the PSF are written in the
e "C" language. T
There are many reasons
r for this approach
a and it has many conseq quences. One of them
t (probably th he most importan
nt) is that
thanks to
o it, Python may be
b easily ported and migrated to alla platforms with h the ability to commpile and run "C" language progrrams (virtually all platforms have this
t
feature, which
w opens up many
m expansion opportunities forr Python).
This is why
w the PSF imple
ementation is often referred to as
s CPython. This is
i the most influe
ential Python amo
ong all the Pythons in the world.
Cytho
on
Another Python family me
ember is Cython
n.
How are these two contra adictions reconcilled? One solution n is to write your mathematical ide eas using Pythonn,
and when you're absolute ely sure that yourr code is correct and produces va alid results, you can
c translate it intto
"C". Certtainly, "C" will run
n much faster thaan pure Python.
This is what
w Cython is intended to do - to automatically tra
anslate the Python code (clean an
nd clear, but not too
t swift) into "C"" code (complicatted and talkative, but
agile).
Jytho
on
Another version
v of Python is
i called Jython.
TECHNOL
LOGIES DE L’INFO
ORMATION/ ISET
T SOUSSE / COUR
RSE OF PYTHON INSTITUTE
N PAGE 16 SUR 299
9
"J" is for "Java". Imagine a Python written in Java instead of C. This is useful, for example, if you deevelop large and co
omplex systems written
w entirely in Jaava and want to ad
dd some
Python fleexibility to them. The
T traditional CPyython may be diffiicult to integrate in
nto such an environnment, as C and Javva live in completeely different worldds and don't share many
m
common ideas.
i
Jython can
n communicate wiith existing Java innfrastructure more effectively. This iss why some projeccts find it usable an
nd needful.
It's a logo
o of the PyPy - a Python within a Python. In otherr words, it represe
ents a Python
environm ment written in Py
ython-like languag
ge named RPyth hon (Restricted Python).
P It is actu
ually a
subset off Python.
In additio
on, PyPy is compattible with the Pythoon 3 language.
There are many more different Pythons in the world. You'll find
d them if you look, but this course will
w focus on CPyth
hon.
TECHNOL
LOGIES DE L’INFO
ORMATION/ ISET
T SOUSSE / COUR
RSE OF PYTHON INSTITUTE
N PAGE 17 SUR 299
TRAVAILLER AVEC PYTHON 3
There are many ways of utilizing Python, especially if you're going to be a Python developer.
an editor which will support you in writing the code (it should have some special features, not available in simple tools); this dedicated editor will give you
more than the standard OS equipment;
a console in which you can launch your newly written code and stop it forcibly when it gets out of control;
a tool named a debugger, able to launch your code step by step and allowing you to inspect it at each moment of execution.
Besides its many useful components, the Python 3 standard installation contains a very simple but extremely useful application named IDLE.
Navigate through your OS menus, find IDLE somewhere under Python 3.x and launch it. This is what you should see: (image)
TECHNOLOGIES DE L’INFORMATION/ ISET SOUSSE / COURSE OF PYTHON INSTITUTE PAGE 18 SUR 299
How to
t write an
nd run yourr very firstt program
It is now time to write and
d run your first Pyython 3 program. It will be very sim
mple, for now.
This is th
he editor windoww. Its only purposse is to be a work
kplace in which your
y source code
e is treated. Do no
ot confuse the ed
ditor window with
h the shell window
w. They
perform different
d functions.
TECHNOL
LOGIES DE L’INFO
ORMATION/ ISET
T SOUSSE / COUR
RSE OF PYTHON INSTITUTE
N PAGE 19 SUR 299
9
Click File
e (in the new wind
dow), then click S
Save as..., selectt a folder for the new file (the desktop is a good place for your first programming attempts) and chos
se a
name forr the new file.
TECHNOL
LOGIES DE L’INFO
ORMATION/ ISET
T SOUSSE / COUR
RSE OF PYTHON INSTITUTE
N PAGE 20 SUR 299
9
Module 2
Python Essentials 1
Data Types, Variables, Basic I/O Operations, and Basic Operators
Data types, variables, basic input-output operations, basic operators
print("Hello, World!")
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:
cause some effect (e.g., send text to the terminal, create a file, draw an image, play a sound, etc.); this is something completely unheard of in the world of mathematics;
evaluate a value (e.g., the square root of a value or the length of a given text) and return it as the function's result; this is what makes Python functions the relatives of
mathematical concepts.
TECHNOLOGIES DE L’INFORMATION/ ISET SOUSSE / COURSE OF PYTHON INSTITUTE PAGE 21 SUR 299
Moreover, many of Python functions can do the above two things together.
They may come from Python itself; the print function is one of this kind; such a function is an added value received together with Python and its environment (it is built-in);
you don't have to do anything special (e.g., ask anyone for anything) if you want to make use of it;
they may come from one or more of Python's add-ons named modules; some of the modules come with Python, others may require separate installation - whatever the case,
they all need to be explicitly connected with your code (we'll show you how to do that soon);
you can write them yourself, placing as many functions as you want and need inside your program to make it simpler, clearer and more elegant.
The name of the function should be significant (the name of the print function is self-evident).
Of course, if you're going to make use of any already existing function, you have no influence on its name, but when you start writing your own functions, you should consider
carefully your choice of names.
an effect;
a result.
Mathematical functions usually take one argument, e.g., sin(x) takes an x, which is the measure of an angle.
Python functions, on the other hand, are more versatile. Depending on the individual needs, they may accept any number of arguments - as many as necessary to perform their tasks.
Note: any number includes zero - some Python functions don't need any argument.
print("Hello, World!")
In spite of the number of needed/provided arguments, Python functions strongly demand the presence of a pair of parentheses - opening and closing ones, respectively.
If you want to deliver one or more arguments to a function, you place them inside the parentheses. If you're going to use a function which doesn't take any argument, you still have to
have the parentheses.
TECHNOLOGIES DE L’INFORMATION/ ISET SOUSSE / COURSE OF PYTHON INSTITUTE PAGE 22 SUR 299
Note: to distinguish ordinary words from function names, place a pair of empty parentheses after their names, even if the corresponding function wants one or more arguments. This
is a standard convention.
print("Hello, World!")
As you can see, the string is delimited with quotes - in fact, the quotes make the string - they cut out a part of the code and assign a different meaning to it.
You can imagine that the quotes say something like: the text between us is not code. It isn't intended to be executed, and you should take it as is.
Almost anything you put inside the quotes will be taken literally, not as code, but as data. Try to play with this particular string - modify it, enter some new content, delete some of the
existing content.
There's more than one way to specify a string inside Python's code, but for now, though, this one is enough.
So far, you have learned about two important parts of the code: the function and the string. We've talked about them in terms of syntax, but now it's time to discuss them in terms of
semantics.
We'll discuss this in more depth soon, but we should just shed a little light on it right now.
print("Hello, World!")
TECHNOLOGIES DE L’INFORMATION/ ISET SOUSSE / COURSE OF PYTHON INSTITUTE PAGE 23 SUR 299
What happens when Python encounters an invocation like this one below?
function_name(argument)
Let's see:
First, Python checks if the name specified is legal (it browses its internal data in order to find an existing function of the name; if this search fails, Python aborts the code);
second, Python checks if the function's requirements for the number of arguments allows you to invoke the function in this way (e.g., if a specific function demands exactly
two arguments, any invocation delivering only one argument will be considered erroneous, and will abort the code's execution);
third, Python leaves your code for a moment and jumps into the function you want to invoke; of course, it takes your argument(s) too and passes it/them to the function;
fourth, the function executes its code, causes the desired effect (if any), evaluates the desired result(s) (if any) and finishes its task;
finally, Python returns to your code (to the place just after the invocation) and resumes its execution.
takes its arguments (it may accept more than one argument and may also accept less than one argument)
converts them into human-readable form if needed (as you may suspect, strings don't require this action, as the string is already readable)
and sends the resulting data to the output device (usually the console); in other words, anything you put into the print() function will appear on your screen.
No wonder then, that from now on, you'll utilize print() very intensively to see the results of your operations and evaluations.
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() .
TECHNOLOGIES DE L’INFORMATION/ ISET SOUSSE / COURSE OF PYTHON INSTITUTE PAGE 24 SUR 299
The print() function - instructions
You have already seen a computer program that contains one function invocation. A function invocation is one of many possible kinds of Python instructions.
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, you can see it in the editor. Run it and note what you see in the console.
the program invokes the print() function twice, and you can see two separate lines in the console - this means that print() begins its output from a
new line each time it starts its execution; you can change this behavior, but you can also use it to your advantage;
each print() invocation contains a different string, as its argument and the console content reflects it - this means that the instructions in the code are
executed in the same order in which they have been placed in the source file; no next instruction is executed until the previous one is completed (there are
some exceptions to this rule, but you can ignore them for now)
TECHNOLOGIES DE L’INFORMATION/ ISET SOUSSE / COURSE OF PYTHON INSTITUTE PAGE 25 SUR 299
You can see it in the editor window. Run the code.
What happens?
As you can see, the empty print() invocation is not as empty as you may have expected - it does output an empty line, or (this interpretation is also correct) its
output is just a newline.
This is not the only way to produce a newline in the output console. We're now going to show you another way.
There are two very subtle changes - we've inserted a strange pair of characters inside the rhyme. They look like this: \n .
Interestingly, while you can see two characters, Python sees one.
The backslash ( \ ) has a very special meaning when used inside strings - this is called the escape character.
The word escape should be understood specifically - it means that the series of characters in the string escapes for the moment (a very short moment) to introduce a
special inclusion.
In other words, the backslash doesn't mean anything in itself, but is only a kind of announcement, that the next character after the backslash has a different meaning
too.
The letter n placed after the backslash comes from the word newline.
Both the backslash and the n form a special symbol named a newline character, which urges the console to start a new output line.
Run the code. Your console should now look like this:
TECHNOLOGIES DE L’INFORMATION/ ISET SOUSSE / COURSE OF PYTHON INSTITUTE PAGE 26 SUR 299
The itsy bitsy spider
climbed up the waterspout.
As you can see, two newlines appear in the nursery rhyme, in the places where the \n have been used.
1. If you want to put just one backslash inside a string, don't forget its escaping nature - you have to double it, e.g., such an invocation will cause an error:
print("\")
print("\\")
2. Not all escape pairs (the backslash coupled with another character) mean something.
Experiment with your code in the editor, run it, and see what happens.
Look at the editor window. This is what we're going to test now:
TECHNOLOGIES DE L’INFORMATION/ ISET SOUSSE / COURSE OF PYTHON INSTITUTE PAGE 27 SUR 299
There is one print() function invocation, but it contains three arguments. All of them are strings.
The arguments are separated by commas. We've surrounded them with spaces to make them more visible, but it's not really necessary, and we won't be doing it
anymore.
In this case, the commas separating the arguments play a completely different role than the comma inside the string. The former is a part of Python's syntax, the
latter is intended to be shown in the console.
If you look at the code again, you'll see that there are no spaces inside the strings.
The spaces, removed from the strings, have appeared again. Can you explain why?
a print() function invoked with more than one argument outputs them all on one line;
the print() function puts a space between the outputted arguments on its own initiative.
You should be able to predict the output without running the code in the editor.
The way in which we are passing the arguments into the print() function is the most common in Python, and is called the positional way (this name comes from
the fact that the meaning of the argument is dictated by its position, e.g., the second argument will be outputted after the first, not the other way round).
Run the code and check if the output matches your predictions.
TECHNOLOGIES DE L’INFORMATION/ ISET SOUSSE / COURSE OF PYTHON INSTITUTE PAGE 28 SUR 299
The print() function - the keyword arguments
Python offers another mechanism for the passing of arguments, which can be helpful when you want to convince the print() function to change its behavior a bit.
We aren't going to explain it in depth right now. We plan to do this when we talk about functions. For now, we simply want to show you how it works. Feel free to use
it in your own programs.
The mechanism is called keyword arguments. The name stems from the fact that the meaning of these arguments is taken not from its location (position) but from
the special word (keyword) used to identify them.
The print() function has two keyword arguments that you can use for your purposes. The first of them is named end .
In the editor window you can see a very simple example of using a keyword argument.
a keyword argument consists of three elements: a keyword identifying the argument ( end here); an equal sign ( = ); and a value assigned to that argument;
any keyword arguments have to be put after the last positional argument (this is very important)
print("Monty Python.")
In our example, we have made use of the end keyword argument, and set it to a string containing one space.
As you can see, the end keyword argument determines the characters the print() function sends to the output once it reaches the end of its positional arguments.
The default behavior reflects the situation where the end keyword argument is implicitly used in the following way: end="\n" .
TECHNOLOGIES DE L’INFORMATION/ ISET SOUSSE / COURSE OF PYTHON INSTITUTE PAGE 29 SUR 299
The print() function - the keyword arguments
And now it's time to try something more difficult.
If you look carefully, you'll see that we've used the end argument, but the string assigned to it is empty (it contains no characters at all).
What will happen now? Run the program in the editor to find out.
As the end argument has been set to nothing, the print() function outputs nothing too, once its positional arguments have been exhausted.
The string assigned to the end keyword argument can be of any length. Experiment with it if you want.
output
TECHNOLOGIES DE L’INFORMATION/ ISET SOUSSE / COURSE OF PYTHON INSTITUTE PAGE 30 SUR 299
The print() function - the keyword arguments
We've said previously that the print() function separates its outputted arguments with spaces. This behavior can be changed, too.
The keyword argument that can do this is named sep (like separator).
Look at the code in the editor, and run it.
print("My", "name", "is", "Monty", "Python.", sep="-")
The sep argument delivers the following results:
My-name-is-Monty-Python.
output
The print() function now uses a dash, instead of a space, to separate the outputted arguments.
Note: the sep argument's value may be an empty string, too. Try it for yourself.
print("1-My", "name", "is", "Monty", "Python.", sep="-")
print("2-My", "name", "is", "Monty", "Python.", sep="")
print("3-My", "name", "is", "Monty", "Python.", sep="/")
output
1-My-name-is-Monty-Python.
2-MynameisMontyPython.
3-My/name/is/Monty/Python.
Now that you understand the print() function, you're ready to consider how to store and process data in Python.
Without print() , you wouldn't be able to see any results.
TECHNOLOGIES DE L’INFORMATION/ ISET SOUSSE / COURSE OF PYTHON INSTITUTE PAGE 31 SUR 299
Exercice 1
Objectives
becoming familiar with the print() function and its formatting capabilities;
experimentingwith Python code.
Scenario
Modify the first line of code in the editor, using the sep and end keywords, to match the expected output. Use the two print() functions in the editor.
print("Programming","Essentials","in")
print("Python")
Expected output
Programming***Essentials***in...Python
Solution
…..
Exercice 2
Objectives
experimenting with existing Python code;
discovering and fixing basic syntax errors;
becoming familiar with the print() function and its formatting capabilities.
TECHNOLOGIES DE L’INFORMATION/ ISET SOUSSE / COURSE OF PYTHON INSTITUTE PAGE 32 SUR 299
Scenario
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.
print(" *") *
print(" * *")
print(" * *") * *
print(" * *")
print("*** ***") * *
print(" * *")
print(" * *") * *
print(" *****")
*** ***
* *
* *
*****
Try to:
minimize the number of print() function invocations by inserting the \n sequence into the strings
make the arrow twice as large (but keep the proportions)
duplicate the arrow, placing both arrows side by side; note: a string may be multiplied by using the following trick: "string" * 2 will
produce "stringstring" (we'll tell you more about it soon)
remove any of the quotes, and look carefully at Python's response; pay attention to where Python sees an error - is this the place where the error really
exists?
do the same with some of the parentheses;
change any of the print words into something else, differing only in case (e.g., Print ) - what happens now?
replace some of the quotes with apostrophes; watch what happens carefully.
TECHNOLOGIES DE L’INFORMATION/ ISET SOUSSE / COURSE OF PYTHON INSTITUTE PAGE 33 SUR 299
Key takeaways
1. The print() function is a built-in function. It prints/outputs a specified message to the screen/consol 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.
Does it represent any value? Maybe. It can be the symbol of the speed of light, for example. It also can be the constant of integration. Or even the length of a hypotenuse in the sense
of a Pythagorean theorem. There are many possibilities.
You cannot choose the right one without some additional knowledge.
And this is the clue: 123 is a literal, and c is not.
You use literals to encode data and to put them into your code. We're now going to show you some conventions you have to obey when using Python.
print("2")
print(2)
output
2
2
The first line looks familiar. The second seems to be erroneous due to the visible lack of quotes.
Try to run it.
If everything went okay, you should now see two identical lines.
What happened? What does it mean?
Through this example, you encounter two different types of literals:
a string, which you already know,
and an integer number, something completely new.
The print() function presents them in exactly the same way - this example is obvious, as their human-readable representation is also the same. Internally, in the
computer's memory, these two values are stored in completely different ways - the string exists as just a string - a series of letters.
The number is converted into machine representation (a set of bits). The print() function is able to show them both in a form readable to humans.
We're now going to be spending some time discussing numeric literals and their internal life.
TECHNOLOGIES DE L’INFORMATION/ ISET SOUSSE / COURSE OF PYTHON INSTITUTE PAGE 35 SUR 299
Integers
You may already know a little about how computers perform calculations on numbers. Perhaps you've heard of the binary system, and know that it's the system computers use for
storing numbers, and that they can perform any operation upon them.
We won't explore the intricacies of positional numeral systems here, but we'll say that the numbers handled by modern computers are of two types:
integers, that is, those which are devoid of the fractional part;
and floating-point numbers (or simply floats), that contain (or are able to contain) the fractional part.
This definition is not entirely accurate, but quite sufficient for now. The distinction is very important, and the boundary between these two types of numbers is very strict. Both of
these kinds of numbers differ significantly in how they're stored in a computer memory and in the range of acceptable values.
The characteristic of the numeric value which determines its kind, range, and application, is called the type.
If you encode a literal and place it inside Python code, the form of the literal determines the representation (type) Python will use to store it in the memory.
For now, let's leave the floating-point numbers aside (we'll come back to them soon) and consider the question of how Python recognizes integers.
The process is almost like how you would write them with a pencil on paper - it's simply a string of digits that make up the number. But there's a reservation - you must not interject
any characters that are not digits inside the number.
Take, for example, the number eleven million one hundred and eleven thousand one hundred and eleven. If you took a pencil in your hand right now, you would write the number like
this: 11,111,111 , or like this: 11.111.111 , or even like this: 11 111 111 .
It's clear that this provision makes it easier to read, especially when the number consists of many digits. However, Python doesn't accept things like these. It's prohibited. What
Python does allow, though, is the use of underscores in numeric literals.*
Therefore, you can write this number either like this: 11111111 , or like that: 11_111_111 .
NOTE *Python 3.6 has introduced underscores in numeric literals, allowing for placing single underscores between digits and after base specifiers for improved readability. This
feature is not available in older versions of Python.
And how do we code negative numbers in Python? As usual - by adding a minus. You can write: -11111111 , or -11_111_111 .
TECHNOLOGIES DE L’INFORMATION/ ISET SOUSSE / COURSE OF PYTHON INSTITUTE PAGE 36 SUR 299
Integers: octal and hexadecimal numbers
There are two additional conventions in Python that are unknown to the world of mathematics. The first allows us to use numbers in an octal representation.
If an integer number is preceded by an 0O or 0o prefix (zero-o), it will be treated as an octal value. This means that the number must contain digits taken from the
[0..7] range only.
print(0o123)
The second convention allows us to use hexadecimal numbers. Such numbers should be preceded by the prefix 0x or 0X (zero-x).
0x123 is a hexadecimal number with a (decimal) value equal to 291 . The print() function can manage these values too. Try this:
print(0x123)
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
Note: two and a half looks normal when you write it in a program, although if your native language prefers to use a comma instead of a point in the number, you should ensure that
your number doesn't contain any commas at all.
TECHNOLOGIES DE L’INFORMATION/ ISET SOUSSE / COURSE OF PYTHON INSTITUTE PAGE 37 SUR 299
Python will not accept that, or (in very rare but possible cases) may misunderstand your intentions, as the comma itself has its own reserved meaning in Python.
If you want to use just a value of two and a half, you should write it as shown above. Note once again - there is a point between 2 and 5 - not a comma.
As you can probably imagine, the value of zero point four could be written in Python as:
0.4
But don't forget this simple rule - you can omit zero when it is the only digit in front of or after the decimal point.
.4
For example: the value of 4.0 could be written as:
4.
This will change neither its type nor its value.
4.0
You may think that they are exactly the same, but Python sees them in a completely different way.
To avoid writing out so many zeros, physics textbooks use an abbreviated form, which you have probably already seen: 3 x 108 .
TECHNOLOGIES DE L’INFORMATION/ ISET SOUSSE / COURSE OF PYTHON INSTITUTE PAGE 38 SUR 299
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
print(0.0000000000000000000001)
1e-22
Python always chooses the more economical form of the number's presentation, and you should take this into consideration when creating literals.
TECHNOLOGIES DE L’INFORMATION/ ISET SOUSSE / COURSE OF PYTHON INSTITUTE PAGE 39 SUR 299
Strings
Strings are used when you need to process text (like names of all kinds, addresses, novels, etc.), not numbers.
You already know a bit about them, e.g., that strings need quotes the way floats need points.
However, there is a catch. The catch is how to encode a quote inside a string which is already delimited by quotes.
The first is based on the concept we already know of the escape character, which you should remember is played by the backslash. The backslash can escape quotes too. A quote
preceded by a backslash changes its meaning - it's not a delimiter, but just a quote. This will work as intended:
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.
TECHNOLOGIES DE L’INFORMATION/ ISET SOUSSE / COURSE OF PYTHON INSTITUTE PAGE 40 SUR 299
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 below to see if you were right:
Check
print('I\'m Monty Python.')
or
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.
TECHNOLOGIES DE L’INFORMATION/ ISET SOUSSE / COURSE OF PYTHON INSTITUTE PAGE 41 SUR 299
Yes, thisistrue;
No, thisis false.
You'll never get a response like: I don't know or Probably yes, but I don't know for sure.
True
False
You cannot change anything - you have to take these symbols as they are, including case-sensitivity.
print(True>False)
print(True<False)
Run the code in the Sandbox to check. Can you explain the result?
Exercice
Objectives
becoming familiar with the print() function and its formatting capabilities;
practicingcoding strings;
experimentingwith Python code.
Scenario
Write a one-line piece of code, using the print() function, as well as the newline and escape characters, to match the expected result outputted on three lines.
TECHNOLOGIES DE L’INFORMATION/ ISET SOUSSE / COURSE OF PYTHON INSTITUTE PAGE 42 SUR 299
Expected output
"I'm"
""learning""
"""Python"""
Solution
…….
Key takeaways
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
TECHNOLOGIES DE L’INFORMATION/ ISET SOUSSE / COURSE OF PYTHON INSTITUTE PAGE 43 SUR 299
There is one more, special literal that is used in Python: the None literal. This literal is a so-called NoneType object, and it is used to represent the absence of a value. We'll tell you
more about it soon.
Exercise 1
TECHNOLOGIES DE L’INFORMATION/ ISET SOUSSE / COURSE OF PYTHON INSTITUTE PAGE 44 SUR 299
Module 3
Python Essentials 1
Boolean Values, Conditional Execution, Loops, Lists and List
Processing, Logical and Bitwise Pperations
MODULE 3: BOOLEAN VALUES, CONDITIONAL EXECUTION, LOOPS, LISTS AND LIST PROCESSING, LOGICAL AND BITWISE OPERATIONS
3.1. Comparisonoperators and conditionalexecution
o 3.1. COMPARISON OPERATORS AND CONDITIONAL EXECUTION
o Python Essentials 1: Module 3
o 3.1.1.1 Makingdecisions in Python
o 3.1.1.2 Makingdecisions in Python
o 3.1.1.3 Makingdecisions in Python
o 3.1.1.4 LAB: Questions and answers Lab
o 3.1.1.5 Makingdecisions in Python
o 3.1.1.6 Makingdecisions in Python
o 3.1.1.7 Makingdecisions in Python
o 3.1.1.8 Makingdecisions in Python
o 3.1.1.9 Makingdecisions in Python
o 3.1.1.10 LAB: Comparison operators and conditional execution Lab
o 3.1.1.11 LAB: Essentials of the if-else statement Lab
o 3.1.1.12 LAB: Essentials of the if-elif-else statement Lab
o 3.1.1.13 SECTION SUMMARY (1/2)
o 3.1.1.14 SECTION SUMMARY (2/2)
3.2. Loops
o 3.2. LOOPS
o 3.2.1.1 Loops in Python | while
o 3.2.1.2 Loops in Python | while
o 3.2.1.3 LAB: Essentials of the while loop - Guess the secret number Lab
o 3.2.1.4 Loops in Python | for
o 3.2.1.5 Loops in Python | for
o 3.2.1.6 LAB: Essentials of the for loop - counting mississippily Lab
o 3.2.1.7 Loop control in Python | break and continue
o 3.2.1.8 Loop control in Python | break and continue
o 3.2.1.9 LAB: The break statement - Stuck in a loop Lab
o 3.2.1.10 LAB: The continue statement - the Ugly Vowel Eater Lab
o 3.2.1.11 LAB: The continue statement - the Pretty Vowel Eater Lab
TECHNOLOGIES DE L’INFORMATION/ ISET SOUSSE / COURSE OF PYTHON INSTITUTE PAGE 45 SUR 299