0% found this document useful (0 votes)
80 views15 pages

Cours Python V3 en-GB

This document provides an introduction to programming with the Python language. It discusses key concepts like algorithms, variables, data types, operators, and libraries. The document also provides examples of Python code and exercises for readers to practice programming concepts like determining the greatest common divisor, simulating coin tosses, and manipulating lists. It is intended to teach programming fundamentals to beginners using the Python language.

Uploaded by

Marisa Vetter
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
0% found this document useful (0 votes)
80 views15 pages

Cours Python V3 en-GB

This document provides an introduction to programming with the Python language. It discusses key concepts like algorithms, variables, data types, operators, and libraries. The document also provides examples of Python code and exercises for readers to practice programming concepts like determining the greatest common divisor, simulating coin tosses, and manipulating lists. It is intended to teach programming fundamentals to beginners using the Python language.

Uploaded by

Marisa Vetter
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1/ 15

Subscribe to DeepL Pro to edit this document.

Visit www.DeepL.com/profor more information.

Introduction to programming
Python language

I). Introduction: Algorithms

The word "algorithm" comes from the name of the 9ème century Uzbek mathematician Al
Khwarizmi.
An algorithm consists of performing a complex task by breaking it down into a succession of
simple tasks: An algorithm is a finite sequence of instructions indicating the precise order in
which a set of operations must be performed to obtain the solution to a given problem.
For each problem, there may of course be several different algorithms that give the solution.

To carry out a task with a computer, it is expressed in the form of an algorithm, using
elementary operations that it knows: a computer program is the translation of an algorithm
into a well-defined language.
The choice of an algorithm is then made according to the simplicity of the operations, the
ease of programming, the number of operations necessary to arrive at the result, the space
occupied in the computer's memory, the time necessary to obtain the result, etc.
These criteria are sometimes difficult to reconcile.

The complexity of an algorithm is the number of elementary operations (additions,


subtractions, multiplications, divisions, comparisons, assignments, etc.) performed during
the execution of the algorithm (average or maximum number of operations). This part will
be discussed later.

II). General information on Python

Python is a very popular programming language created in 1991. Its main advantage is a
simple syntax that allows even beginners to write complex code without having to worry
too much about the syntax.

It is an interpreted language, which means that lines of code are read and executed one
after the other when processing a program. (no compilation unlike Java or Turbo Pascal)

Python is used in a wide range of applications (science, of course, but also game creation)
and in all countries, at school or university level.

I started by using PyScripter, installed on my computer, for the corrections of the first
exercises, which explains the slight difference between the display of my first results and
those obtained with Python. But I had difficulties installing this software on my second
computer, so I preferred to go back to the basics.

DR RIMA CICCARESE - JEAN-PIERRE DENIER - ESM 1


We will therefore use the latest version of Python downloaded from the official website;
https://www.python.org/downloads/
Classic installation of a software under Windows.

Launch the IDLE program: the Shell appears Click on New File, the editor appears

To run a "Run" program: you must first give it a name.


The result will be written in the Shell (also called Python console).

You can also, without installing the software on your computer, test your programs directly
online: https://www.onlinegdb.com/online_python_compiler or
https://www.codabrainy.com/python-compiler/ and retrieve your work by email.
All examples in this introduction will be handled with version 3.8.3.

DR RIMA CICCARESE - JEAN-PIERRE DENIER - ESM 2


III) What is a programme?

Example:
I am looking to hang a frame on the wall.
1st step: I determine the nature of the wall (concrete, plaster...), the place of the frame, the
tools and objects needed (dowel, drill, meter....). Now that the problem is analysed, I can
move on to the execution.
2nd step: in Bricolo-Python, my algorithm would be written as follows;
program hang_frame ; (the name of the program, to be given before execution)
tools
stepladder, pencil, mechebeton, meter, drill ;
supplies
peg, hook ;
var (Define variables of type int, float, list...)
height = 1.7 (float variable)
start of "operations
measure the height of the hole
mark location with pencil
plug in drill ;
if height>1m70 :
use stepladder (indentation: 4 indents)
drill wall
place ankle
screw on hook
place frame
Run ;

Remarks :
 This example assumes, of course, that you do not live under a bridge, but statistically
this is highly unlikely in the world of ESM students.
 More seriously, writing a program uses the same approach and is no more
complicated once you have mastered the syntax of the language.

IV). Features of Python

The main feature of Python is the use of indentation (automatic indentation of text, or
shifting to the right), whereas other languages require the use of 'begin' and 'end' keywords
to delimit blocks. This reduces the risk of syntactic errors in Python.
A simple example:
for i in range(6):

And in Python : print(i) Indentation

Indentation

DR RIMA CICCARESE - JEAN-PIERRE DENIER - ESM 3


V).the variables
1). Statement
Another important feature is the way variables are declared. For example, by writing
"x=2", Python understands that the variable (or memory cell) x is of integer type. If later in
the same program we write "x=0.5", the variable x will have become a decimal number of
type float.
2). Types of variables x = 100
y = 0.5
 As we have already noted, the "integer" and "float" variables

a = 2 + 3j
 The third type of numerical variable is the "complex":
b = 5 - 4j

 Booleans: these are logical variables that only take the values "True" and "False".
Indispensable for tests.
 Lists. Less useful in Mathematics, but very practical for a "clean" presentation of
results. Letters and numbers are allowed in a list.

list1 = [12, 15, 8, 9] list1 = ["value", 5, 2.3]


print(list1) print(list1)

Exercise 1:
Analyse the script :

DR RIMA CICCARESE - JEAN-PIERRE DENIER - ESM 4


VI) Main operators in Python
1) Arithmetic operators
 + : addition
 - subtraction
 * : multiplication
 ** : power
 / : division
 Modulus: a % b returns the remainder of the division of a by b (56 % 9 gives 2)

As we will see later, the "math" library, which needs to be called often in our mathematical
programs, is not necessary here for the recognition of these 6 operations.
Example of use: Python console (or Shell) used as a calculator.

Note:
Division always gives a float result, but you can "force" an integer result with "//".

DR RIMA CICCARESE - JEAN-PIERRE DENIER - ESM 5


Note:
We have two operations on strings: + and *.

Exercise 2:
Determine the GCD of 654 and 780 (Use the Python console)
2). Assignments
The main assignment is the "=" symbol
Example: x=5; y=3 means that 5 is placed in the x memory box, and 3 in y. You should never
write "5=x".

In fact, it should be understood: . We place 5 in x. (notation used by other languages)


3). Comparison (or relational) operators
a) "Symbol repeated to differentiate it from simple =.
b) "different from: " != "
c) "Strictly smaller than": " < " 8>3 is True while 8<3 is False
d) "strictly greater than": ">".
e) "less than or equal to": "<=".
f) "Greater than or equal to": ">=".

4). Logical (or Boolean) operators


a) The "and" binary: "and".
b) The "or binary": "or" (always inclusive)
c) Binary negation": "not
These operations concern either true or false expressions (i.e. Boolean expressions). For
more details, see Appendix 1 at the end of the handout.

DR RIMA CICCARESE - JEAN-PIERRE DENIER - ESM 6


Exercise 3:
N is a whole number. When will the answer to the test "N % 3==1" be true?

5). Priority orders


The same as in mathematics!
6). Useful instructions for lists
In this sub-section, some essential instructions for manipulating lists.
 The len( ) function returns the length of the list. list1 = [12, 15, 8, 9]
len(list1)
The value returned here is 4.
 List1[0] is 12, list1[3] is 9
 Add an element to a list: append( ) list1 = [12, 15, 8, 9]
list1.append(10)
list1 becomes [12, 15, 8, 9, 10]: 10 is added at the end.
 The remove( ) function. list1.remove(15)

list1 becomes [12, 8, 9, 10]


7). Essential libraries
Essential (or useful) libraries for us are "math", "random", "cmath", "fractions"... The syntax
is: from ..... import *

Exercise 4:

DR RIMA CICCARESE - JEAN-PIERRE DENIER - ESM 7


Calculate: and .
Exercise5 :
Simulate a sequence of 5 tosses of a balanced coin in the game of Heads or Tails.
VII).identifiers

An identifier is a string of alphanumeric characters chosen by the user to give a name to an


entity used in the program (program, constants, variables, types, functions, procedures,
etc.).
Any Python identifier must check the following 3 rules:
1) start with a letter,
2) contain only letters, numbers, or the character "_". There must be no free spaces.
3) not to reproduce a reserved word from the Python language. (for example "remove")

Warning: Python is case sensitive, i.e. "S7_5P" is different from "S7_5p".


The computer allocates an address in its memory to each identifier, and at this address it
successively puts all the values taken by it (assignment).
To assign a value to an identifier, the following procedure is used:
height =1.7; the height identifier, of type float, takes the value 1.7.
It is important to note that the assignment symbol "=" can only be read in one direction.
Other computer languages use " " which is less error-prone (see 1.7).

VIII). Input and output instructions

1). The "print" instruction


It allows you to display a sentence, or the display of a variable.

2). The "input" instruction


This instruction allows the computer to read values and assign them to variables.
Attention:
When you want to enter a number, you must specify the nature of the number. (remember
the difference between words and letters)

DR RIMA CICCARESE - JEAN-PIERRE DENIER - ESM 8


IX). Structured instructions

1). Conditional statements: if / elif / else


The "if" is used when a block must be executed only if a condition is met.
The block to be executed if the condition is not met is preceded by "else".
If the conditions are multiple, then "elif" is used. (otherwise if)
Example 1:
Algorithm and program to determine the maximum of two numbers.
Already used: "#" allows you to insert an explanatory text, which will not be interpreted by
the program.

Example 2:

DR RIMA CICCARESE - JEAN-PIERRE DENIER - ESM 9


Example 3: You should understand what this is about!
Note the need to load the Python Math library at the start of the program.
We need the sqrt( ) function, i.e. .

In each example, the entered term needs to be converted to a number (float or int).
2). The simple "for" loop (loop = loop)

DR RIMA CICCARESE - JEAN-PIERRE DENIER - ESM 10


It is used when a piece of code needs to be repeated a defined number of times.
An example is the calculation of the first 5 multiples of 7:

The program will return: 7, 14, 21, 28, 35. When i reaches the value 6, the loop is exited. (No
calculation is performed with 6, only the loop exit)
Note that there is no need to define "i" before using it.
The full syntax is: range(start value, end value, step).
You can increment or decrement (decrease) in a loop.
Another example, which gives exactly the same result: 7, 14, 21, 28, 35.

As soon as "i" reaches the value 0, the loop is exited without calculation. The decrement is: -
1.
Exercise 6:
Write a script to determine the divisors of an integer.
Exercise 7:

Write a program to calculate :


3). The "while" conditional loop: as long as
This loop is executed as long as a condition is verified: beware, it can theoretically run
indefinitely.
Example: Euclidean division using the "while" loop.

DR RIMA CICCARESE - JEAN-PIERRE DENIER - ESM 11


The "while" loop will be executed as long as the "remainder" variable is greater than or
equal to the "divisor" variable, which represents the divisor.
In this example, it is not necessary to import the "math" library.
Note: It is also possible to "loop" within a list.
Example:

It is not necessary to know precisely the length of the list to implement the loop. The small
program above will write one after the other the values 12, then 15...
Exercise 8:
Write a program that determines how many times an integer is divisible by 2.
Exercise 9:
Write a program that calculates how many years are needed to double a capital invested
with compound interest at a rate of t %. (input variable: t of type float)
Exercise 10:
Write a program that determines the GCD of two given integers.
X). The functions
Functions are a script that is assigned the task of returning a particular value.
A function is defined using the keyword "def", followed by the name of the function with
the list of arguments or variables in brackets. The two dots are still essential. Be careful of

DR RIMA CICCARESE - JEAN-PIERRE DENIER - ESM 12


the order in which you define the variables. The "return" keyword indicates which value
should be returned (function "image" value).
Example 1:
Heads or tails game. This is what the code looks like, with 5 throws:

Again, it is necessary to import the "random" library.


It can also be noted that the "corner" function requires no arguments.
Note:
 the function random() returns a random number between 0 and 1
 random.choice, random.choices()...are other functions of this library.

Example 2:
In Python, the predefined "math" function gcd (a,b) gives the PGCD of two integers a and b.
No function gives the PPCM.
We will therefore use the following mathematical property: PGCD(a,b)xPPCM(a,b)=axb.

DR RIMA CICCARESE - JEAN-PIERRE DENIER - ESM 13


Example 3:
We wish to represent the graph of : f ( x )=x 2.
Using the "matplotlib" library, which must be installed specifically in addition to Python, we
obtain :

 x is the list [-100,-99,....,99,100]


 y is the list [f(-100),f(-99),....,f(99),f(100)]

DR RIMA CICCARESE - JEAN-PIERRE DENIER - ESM 14


Exercise 11:
Create a function PGCD, which, using Euclid's algorithm, determines the PGCD of two
integers. (without using the function "gcd" of course)
Exercise 12:
Create a PREM function that determines whether an integer greater than or equal to 2 is
prime (without using isPrime which exists in Python)
Exercise 13:
Using your previous function PREM (slightly modified), create a function that gives the nth
prime. We will call it NPREM. (Start by checking that 7 is the 4th prime)

End of this initiation

DR RIMA CICCARESE - JEAN-PIERRE DENIER - ESM 15

You might also like