Python Corso Cascioli
Python Corso Cascioli
PROGRAMMING
Gael Cascioli
30/11/21
[email protected]
OUTLINE
”Programming” consists in writing a set of instructions to implement algorithms (or procedures) to be executed by a
computer.
The language we use to communicate with the computer is the “programming language”
The classical example:
The language
The set of instructions
Pros: Pros:
Fast, Precise Easy to understand
Cons: Cons:
Difficult for humans to read Slower to convert to machine-
code (i.e., lower speed)
Cow
Generate the Fibonacci sequence:
MoO moO MoO mOo MOO OOM MMM moO moO MMM mOo mOo moO MMM mOo MMM moO
moO MOO MOo mOo MoO moO moo mOo mOo moo
Malbolge
Print “Hello World”:
(=<`:9876Z4321UT.-Q+*)M'&%$H"!~}|Bzy?=|{z]KwZY44Eq0/{mlk** hKs_dG5[m_BA{?-
Y;;Vb'rR5431M}/.zHGwEDCBA@98\6543W10/.R,+O<
Programming languages can also be distinguished between compiled and interpreted. The main difference consists
in how and when the language is translated in machine code.
Compiled Interpreted
Pros: Faster, more control on hardware implementation Pros: Platform independent
Cons: Additional step before testing, platform dependent Cons: Slower execution
Source: qvik.com
Elaborated by rednonk.com
• Completely compatible with open source standards 11 Swift
12 Objective-C
• It’s free! 13 Scala
13 R
15 Go
It can be easily interfaced with low-level languages 15 Shell
• Very easy to build Python interfaces to fast-running programs in C/FORTRAN/etc.. 17 PowerShell
18 Perl
19 Kotlin
The Python community is LARGE 20 Haskell
Notable users
Installation
“Conda is an open-source package management system and environment management system that runs on
Windows, macOS, and Linux. Conda quickly installs, runs, and updates packages and their dependencies.
Conda easily creates, saves, loads, and switches between environments on your local computer. It was created
for Python programs but it can package and distribute software for any language.”
Anaconda: https://docs.conda.io/projects/conda/en/latest/user-guide/install/
Windows: https://phoenixnap.com/kb/how-to-install-python-3-windows
macOS: https://docs.python-guide.org/starting/install3/osx/
Linux: https://docs.python-guide.org/starting/install3/linux/
Once installed, it is time to write and run the first python program.
Ok. But how, where??
• PyCharm
• Visual Studio Code
• Atmo
• PyDev
• Spyder
• PyCharm
• Visual Studio Code
• Atmo
• PyDev
• Spyder
• Jupyter Notebook
• iPython
• Google CoLab
Basic variable types in python can be distinguished in data types and data containers
The containers, as per their name, are used to contain the previously defined data types.
Each container is designed for a specific use (we will go in more detail later)
a = 2 a = 'Python’ Output
b = 3 Output b = 'Course' print(a+b) ‘PythonCourse’
print(a+b) 5 print(a + ' ' + b) ‘Python Course’
print(a-b) -1 print(2*a) ‘PythonPython’
print(a*b) 6
print(a/b) 0.6666666
print(a**b) 8
Lists
Lists are used to store multiple items in a single variable.
Lists
Lists are changeable
List operations:
a = [1,2,3]
b = ['A', 'B', ‘C’] Output
Dictionaries
Dictionaries are used to store data in key : value pairs
A dictionary is a container which is ordered (As of Python version 3.7 dictionaries are ordered. In 3.6 and earlier they are
unordered)
Example:
car = { 'Brand': 'FIAT’,
'Model': 'Multipla’,
'year' : 2001,
}
Example: Output
print( car['Model'] ) ‘Multipla’
Dictionaries can be extremely useful when manipulating datasets that are naturally ordered as key:value.
Take as an example a list of employees. Every employee has its personal information (e.g., telephone number, address, …)
employees = {
'Mario Rossi’: { 'Phone Number' : 625,
'Desk Number' : 21,
'Role': 'Financial Advisor’,
},
'Luisa Verdi': { 'Phone Number' : 226,
'Desk Number' : 11,
'Role': 'HR Manager’,
},
...
}
If we need the record of any employee (e.g., Maria Bianchi) we will just need to call:
employees['Maria Bianchi’]
If we need her phone number:
employees['Maria Bianchi']['Phone Number']
The control flow consists in the set of constructs used to control the execution flow of a code.
This means to control when and how to execute parts of the code
- Iterative constructs
a part of the code gests executed zero or more times
- Fundamental constructs
Functions, methods, …
General syntax:
if condition1:
do something
elif condition2:
do something
elif condition3: N.B.
do something
Indenting the code is FUNDAMENTAL
...
elif conditionN:
do something
else:
do something
Condition specification:
The condition(s) to be satisfied uses the common logical operators:
- comparison: <, <=, >, >=, ==, !=
- Identity: is, is not
- Membership: in, not in
- Logical: not, and, or
Examples:
x = 20 x = [1,2,3]
x = 20
if x == 20: if 1 in x:
if x<10:
print('This is 20’) print('Ok!’)
print('Small’)
else: else:
elif 10<=x<=20:
print('This is not print('Not Ok!')
print('Medium’)
20')
elif 20<x<30:
print('Large’)
else:
print('Very Large')
Other examples:
The main iterative construct is the for construct. It allows to execute a block of code a defined
number of times
We have used the range() built-in function. This function is very useful to generate a list of integer numbers.
Example: Given a list of words, construct a sentence with the proper spacing between words
print(mysentence)
Output
The while statement allows to execute a block of instructions indefinitely until a particular condition is True
Example: Sum the natural numbers until their sum is lower than 2000
control_flag = True
sum_of_numbers = 0
number = 0
while control_flag:
if sum_of_numbers + number < 2000:
sum_of_numbers += number
number +=1
else:
control_flag = False
def celsius2farenheit(C):
F = C*1.8 - 32
return F
def farenheit2celsius(F):
C = (F-32)/1.8
return C
def celsius2farenheit(C):
t = 80
F = C*1.8 - 32
return F
t_conv = celsius2farenheit(t)
print(t_conv)
def farenheit2celsius(F):
>> 112.0
C = (F-32)/1.8
return C
t_conv = temperature_converter(t, mode = 'c2f ’)
print(t_conv)
def temperature_converter(T, mode = None):
>> 112.0
if mode is None:
print('Error: A conversion mode must be defined’)
t_conv = temperature_converter(t, mode = 'cf ’)
elif mode == 'c2f ’:
print(t_conv)
return celsius2farenheit(T)
>> Error: A conversion mode must be defined
elif mode == 'f2c’:
return farenheit2celsius(T)
else: print('Error: Conversion mode not recognized')
t = 80
t_conv = generic_converter(t, conversion_function = celsius2farenheit)
print(t_conv)
>> 112.0
Object-oriented programming (OOP) is a programming paradigm that provides a means of structuring programs so
that properties and behaviors are bundled into individual objects.
OOP is an approach to model concrete things, define their properties and the relationship between things.
An object has
- Properties
- Methods
An example:
Object properties
We can have our object to do something more interesting. We can add an object method. An object method is a
function that operates on the object
R.is_square( )
(it)self
We can also define a method that operates on other objects. For example we would like to compare the area of two
rectangles:
Another important aspect when defining objects, is that we can define the relationship rules.
For example, once defined the two rectangles R and A, I would like to know if R>A or R<A.*
So, in my code I’d like to be able to write:
It is possible to define the behavior of standard operations (e.g., +, -, *, >, <, ==, !=, etc) by the so-called
Operator Overloading
Take as example the functions and classes we have defined before. You can write the classes/functions definition in a
python file (e.g., mylibrary.py)
This way you can easily re-use the code you have already written in another script / from the command line / in another
project:
This way you can logically organize you code in several files. (E.g., only one main file)
Apart from defining your own module, you can import external modules (i.e., modules written by others).
One of the most known is numpy (numeric python) which contains many mathematical functions and algorightms.
Suppose you want to create a list of num numbers equally spaced between two extremes a,b
Using numpy you can do exactly the same thing in one line
The main external modules (that usually come directly embedded in the conda installation)
Disclaimer:
Scripting
Scientific plotting
Tutorials:
https://www.w3schools.com/python/default.asp
https://www.tutorialspoint.com/python/index.htm
Stack overflow (i.e., where to ask questions and look for already solved problems):
https://stackoverflow.com