0% found this document useful (0 votes)
24 views

Python Corso Cascioli

Uploaded by

weben.fad
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
24 views

Python Corso Cascioli

Uploaded by

weben.fad
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 58

INTRODUCTION TO PYTHON

PROGRAMMING
Gael Cascioli

30/11/21
[email protected]
OUTLINE

• What is a programming language?


• Why Python?
• How to use Python?
• Basics
• Basic data types with examples
• Control flow
• Functions
• Object oriented programing (brief introduction)
• Modules
• Advanced examples
• Scripting in python
• Scientific plotting
• Analyzing geospatial data
• Useful resources

Introduction to Python programming 30/11/21 2


WHAT IS A PROGRAMMING LANGUAGE?

Introduction to Python programming 30/11/21 3


WHAT IS A PROGRAMMING LANGUAGE?

”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:

A fancy bartender/barlady You at home

The programmer The computer

The language
The set of instructions

Introduction to Python programming 30/11/21 4


WHAT IS A PROGRAMMING LANGUAGE

• A programming language is an agreement between the human and the computer


• Thousands of languages have been invented

Two main classes

Low Level High Level

Closer to machine code Closer to human language


(100110..)

Pros: Pros:
Fast, Precise Easy to understand

Cons: Cons:
Difficult for humans to read Slower to convert to machine-
code (i.e., lower speed)

Introduction to Python programming 30/11/21 5


WHAT IS A PROGRAMMING LANGUAGE

Bonus: Esoteric languages


https://en.wikipedia.org/wiki/Esoteric_programming_language

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<

Introduction to Python programming 30/11/21 6


WHAT IS A PROGRAMMING LANGUAGE

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.

Compiler Machine code Run


Compiled
Language

Run Virtual machine Machine code


Interpreted

Compiled Interpreted
Pros: Faster, more control on hardware implementation Pros: Platform independent
Cons: Additional step before testing, platform dependent Cons: Slower execution

Introduction to Python programming 30/11/21 7


HOW TO CHOOSE ONE?

The main criterion for the choice is the intended


usage.

The intended usage defines the requirements in terms


of
- Execution speed
- Robustness
- Development speed

Source: qvik.com

Introduction to Python programming 30/11/21 8


WHY PYTHON?

Introduction to Python programming 30/11/21 9


WHY PYTHON?

Python implements a high level of abstraction 1 JavaScript


• Easy to read and debug 2 Python
2 Java
• Automatic memory handling 4 PHP
• It is object-oriented 5 C#
6 C++
7 Ruby

Popularity on GitHub (2021)


It is open source 7 CSS
9 TypeScript
• The intellectual property behid the code is held by a non-profit organization 9C

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

Gives you a very good answer 99% of


the times!

Introduction to Python programming 30/11/21 10


WHY PYTHON?

Notable users

Introduction to Python programming 30/11/21 11


HOW TO USE PYTHON?

Introduction to Python programming 30/11/21 12


HOW TO USE PYTHON

Installation

The first thing to do is install python.


It can be done in several ways depending on the OS (windows, macOS, linux, …)

The easiest way: Install (ana)Conda!

“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.”

Introduction to Python programming 30/11/21 13


HOW TO USE PYTHON

Useful links for installing python:

The easy way:

Anaconda: https://docs.conda.io/projects/conda/en/latest/user-guide/install/

The other way:

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/

Introduction to Python programming 30/11/21 14


HOW TO USE PYTHON

Once installed, it is time to write and run the first python program.
Ok. But how, where??

The standard procedure is the following:


1) Write the program
2) Execute the program

There exist several ways of doing this:

1) The hardcore way


2) The fancy way
3) Many other ways

Introduction to Python programming 30/11/21 15


HOW TO USE PYTHON

The hardcore way: Only using the terminal

Introduction to Python programming 30/11/21 16


HOW TO USE PYTHON

The fancy way: Using an IDE


(Integrated Development Environment)

For example: SublimeText

But there are many others:

• PyCharm
• Visual Studio Code
• Atmo
• PyDev
• Spyder

Introduction to Python programming 30/11/21 17


HOW TO USE PYTHON

The fancy way: Using an IDE


(Integrated Development Environment)

For example: SublimeText

But there are many others:

• PyCharm
• Visual Studio Code
• Atmo
• PyDev
• Spyder

Introduction to Python programming 30/11/21 18


HOW TO USE PYTHON

Many other ways:

• Jupyter Notebook

• iPython

• Google CoLab

Introduction to Python programming 30/11/21 19


BASICS

Introduction to Python programming 30/11/21 20


BASICS

Basic data types:

Python is a dynamically and strongly typed language

The data types are imposed.


The type of variable (int, float, string, etc..) is E.g., an integer cannot be treated as a
determined at execution time string without an explicit conversion

Introduction to Python programming 30/11/21 21


BASICS

Basic variable types in python can be distinguished in data types and data containers

Data Type Name in python Example


Integer int 3
Floating-point float 2.43
Complex complex 2+4j
String str ‘Hello world!’
Boolean value bool True or False

You can always check what is tye type of a variable:

Introduction to Python programming 30/11/21 22


BASICS

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)

Data Container Name in python Example


List list [1,2,3,4]
Dictionary dict {‘Cat’: ‘Black’, ‘Dog’: ‘Brown’}
Tuple tuple (1,2,3,4)
Set set {1,2,3,4}

Introduction to Python programming 30/11/21 23


SOME EXAMPLES

Operations on numbers Operations on Strings

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

Introduction to Python programming 30/11/21 24


SOME EXAMPLES

Lists
Lists are used to store multiple items in a single variable.

Example: mylist = ['Python', 'Programming', 'Language’]


mylist2 = [2,3,1,-1,0.4]

Lists are ordered and they can contain duplicates.

Example: mylist = ['A', 'B', ‘C’, ‘C’]


Indexes in Python always
Output start from 0:
print(mylist[0]) 'A’
print(mylist[1]) ‘B’ First element: 0
print(mylist[2]) ‘C’ Second element: 1
print(mylist[3]) ‘C' Third element: 2

Introduction to Python programming 30/11/21 25


SOME EXAMPLES

Lists
Lists are changeable

Example: mylist = ['A', 'B', 'C’]


Output
mylist[0] = 'F’
[‘F', 'B’, 'C’]
print(mylist)

Lists can contain different data types

Example: mylist = [3, 2+4j, True, 'A', 2.33221]

Introduction to Python programming 30/11/21 26


SOME EXAMPLES

List operations:

a = [1,2,3]
b = ['A', 'B', ‘C’] Output

print( a+b ) [1,2,3,’A’,’B’,’C’]


print( 2*a ) [1,2,3,1,2,3]
print( len(a) ) 3
print( a.append(4) ) [1,2,3,4]

Introduction to Python programming 30/11/21 27


SOME EXAMPLES

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,
}

To access an item you can simply call its key

Example: Output
print( car['Model'] ) ‘Multipla’

Introduction to Python programming 30/11/21 28


SOME EXAMPLES

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']

Introduction to Python programming 30/11/21 29


CONTROL FLOW

Introduction to Python programming 30/11/21 30


CONTROL FLOW

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

The main classification of the control flow constructs is:


- Conditional constructs
The execution of the code depends on some condition

- Iterative constructs
a part of the code gests executed zero or more times

- Fundamental constructs
Functions, methods, …

Introduction to Python programming 30/11/21 31


IF STATEMENT

The main conditional construct is the if clause.

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

Introduction to Python programming 30/11/21 32


IF STATEMENT

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')

Introduction to Python programming 30/11/21 33


IF STATEMENT

Other examples:

mylist = [1,2,3] control_flag = True


number1 = 1
number2 = 3 if control_flag:
do something
if (number1 in x) or (number2 in x): else:
print('Ok!’) do something else
else:
print('Not Ok!')

Introduction to Python programming 30/11/21 34


ITERATIVE CONSTRUCTS

The main iterative construct is the for construct. It allows to execute a block of code a defined
number of times

Examples Compute the sum of natural numbers


Create a list with numbers from 0 to 9 from 0 to 1000
mylist = [] sum_of_numbers = 0

for i in range(10): for i in range(1001):


mylist.append(i) sum_of_numbers += i

We have used the range() built-in function. This function is very useful to generate a list of integer numbers.

The generic call to the range function is the following:


range(start, stop, step = 1)

Note: range(start, stop) generates numbers from start to stop-1

Introduction to Python programming 30/11/21 35


ITERARTIVE CONSTRUCTS

Example: Given a list of words, construct a sentence with the proper spacing between words

mylist = ['These', 'are', 'the', 'words', 'of',


'a', 'sentence’]
mysentence = ‘’

for word in mylist:


mysentence += word
mysentence += ' ‘

print(mysentence)

Output

‘These are the words of a sentence’

Introduction to Python programming 30/11/21 36


ITERATIVE CONSTRUCT

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

Introduction to Python programming 30/11/21 37


FUNCTIONS

Introduction to Python programming 30/11/21 38


FUNCTIONS

A function is a block of code that only runs when it is called.


They can be extremely useful when some task has to be repeated many times with different inputs.

Example: Conversion between Celsius and Farenheit


°𝐹=°𝐶 ×1.8 −32
°𝐶=(°𝐹−32)/1.8

def celsius2farenheit(C):
F = C*1.8 - 32
return F

def farenheit2celsius(F):
C = (F-32)/1.8
return C

Introduction to Python programming 30/11/21 39


FUNCTIONS

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')

Introduction to Python programming 30/11/21 40


FUNCTIONS

Functions inputs are divided in


- Positional arguments
- Keyword arguments

def a_generic_function(arg1, arg2, ..., kwarg1 = def1, kwarg2 = def2, ... ):

Functions can take as input other functions:

def generic_converter(T, conversion_function = None):


return conversion_function(T)

t = 80
t_conv = generic_converter(t, conversion_function = celsius2farenheit)
print(t_conv)
>> 112.0

Introduction to Python programming 30/11/21 41


OBJECT-ORIENTED PROGRAMMING

Introduction to Python programming 30/11/21 42


OBJECT ORIENTED PROGRAMMING (BRIEF INTRODUCTION)

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

Introduction to Python programming 30/11/21 43


OBJECT ORIENTED PROGRAMMING (BRIEF INTRODUCTION)

An example:

We want to define an object representing a rectangle


Later we want to use this object to build two different rectangles and compare them

A rectangle is uniquely defined by the length of its sides a and b.


a
The ”rectangle” object should be able to store information about the properties of
the rectangle (e.g., the area and the perimeter)
b

Introduction to Python programming 30/11/21 44


OBJECT ORIENTED PROGRAMMING (BRIEF INTRODUCTION)

Initialization of the object

Object properties

Introduction to Python programming 30/11/21 45


OBJECT ORIENTED PROGRAMMING (BRIEF INTRODUCTION)

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

The method is_square() operates on the properties of the


object itself

The meaning of self :

R.is_square( )

(it)self

Introduction to Python programming 30/11/21 46


OBJECT ORIENTED PROGRAMMING (BRIEF INTRODUCTION)

We can also define a method that operates on other objects. For example we would like to compare the area of two
rectangles:

Introduction to Python programming 30/11/21 47


OBJECT ORIENTED PROGRAMMING (BRIEF INTRODUCTION)

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

* Here by “greater than” we refer only to the area

Introduction to Python programming 30/11/21 48


OBJECT ORIENTED PROGRAMMING (BRIEF INTRODUCTION)

Introduction to Python programming 30/11/21 49


MODULES

Introduction to Python programming 30/11/21 50


MODULES

Modules (also known as libraries) are collections of (typically) functions.


Modules become extremely useful when writing long programs, to logically organize the code.

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:

import mylibrary from mylibrary import temperature_converter


R = mylibrary.Rectangle(20,3, 'R') t = temperature_converter(40, mode = 'c2f')

This way you can logically organize you code in several files. (E.g., only one main file)

Introduction to Python programming 30/11/21 51


EXTERNAL MODULES

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

Introduction to Python programming 30/11/21 52


EXTERNAL MODULES

Using numpy you can do exactly the same thing in one line

Introduction to Python programming 30/11/21 53


EXTERNAL MODULES

The main external modules (that usually come directly embedded in the conda installation)

Module Name Usage


numpy Numerical operations (arrays, matrices,
linear algebra, …)
scipy Numerical methods (optimization,
interpolation, integration, differential
equations, …)
matplotlib Plotting data
os Interact with operating system
sys Interact with operating system
pandas Manage large datasets

Introduction to Python programming 30/11/21 54


EXTERNAL MODULES

External modules need to be installed.

The general way of doing this is:

(If using anaconda)

>> conda install modulename

(If not using anaconda)

>> pip install modulename

Disclaimer:

Always refer to the module website for installation informations.

Introduction to Python programming 30/11/21 55


ADVANCED EXAMPLES

Introduction to Python programming 30/11/21 56


ADVANCED EXAMPLES

Scripting

Scientific plotting

Geospatial data visualization

Introduction to Python programming 30/11/21 57


USEFUL RESOURCES

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

Introduction to Python programming 30/11/21 58

You might also like