Beruflich Dokumente
Kultur Dokumente
2019
Lesson 1
Giovanni Trappolini
Francesco Palini
Schedule
- giovanni.trappolini@uniroma1.it
- francesco.palini@uniroma1.it
Introduction
- Lots of packages
- Simple
- Readable
- Easy to learn
- Lots of support
- Portable
- Free!
Why choose Python? (2)
#include <iostream>
using namespace std;
int main() {
count << “Hello World!” << endl;
}
Why choose Python? (4)
print(“Hello World!”)
Python’s toolset
- Python (v 3.7.4)
- The most used Data Science libraries
- Spyder
- Jupyter
Spyder
The code (or source code) can be written using any text editor, however can be
painful without an environment that:
Usually, when you run a program and you want to obtain a result (or output).
GitHub is a web site in which you can maintain and share your programs (you
can think to a cloud storage). However, It can be much more than this! (e.g.
GitHub.io).
Let’s subscribe to GitHub, the Pro version is free for student accounts!
Git is a popular version control system (VCS) that allows you to keep track of
changes in a directory. In particular, it is used to track changes in source code.
The Python interpreter is a tool which reads and execute Python code line-by-line
in an interactive way.
A variable is a name identifying the memory address in which are saved data.
From an higher point of view, a variable is simply an alias for a particular data.
E.g.
semicolon and data type aren’t needed!
x=5
y=6
z=x+y-2
a, b = 3, 6
the same variable with different data type!
x = “Spoiler alarm! This is a string”
Numbers
In Python 3, the division operator / returns always a float value. You can obtain
an integer division result with the operator //.
Booleans
- True == 1
- False == 0
You can write boolean expressions of variables and values using comparison or
boolean operators.
Comparisons
The symbols shown into the table can be used to compare or evaluate objects.
The result is a boolean value, i.e. True or False.
E.g. ‘hello’ == ‘world’, 3 < 5, ...
Boolean Operations
With these symbols you can build more complex boolean expressions.
E.g. (3 < 5) and ((4 == 5) or (3 <= 10)) the parenthesis are not necessary here
but the use is suggested to avoid errors
Operators Precedence
Strings
Python can manage also the String type. A string can be declared enclosing the
word in single quotes ‘ ’ or double quotes “ ”. The character type, doesn’t exist!
E.g. “I am a string”, ‘I am also a string’, “I’m writing right”, ‘...so, not “bad”!’
Feature: what you expect from ‘ab’ * 5 and from ‘ab’ + ‘cd’ ?
YES! ‘ab’ * 5 = ‘ababababab’ and ‘ab’ + ‘cd’ = ‘abcd’
Substrings
A String object can be accessed indexing the characters using the following
syntax: string[idx] or string[from:to] or string[from:to:step]
Note: the index starts from 0!
E.g.
“ehi man!”[0] #e
“ehi man!”[1:5] # hi m
“ehi man!”[-1] #! Reverse indexing!
“ehi man!”[::2] # eimn Implicit indexing. Starts from 0
String functions
- input(msg): Asks for a value showing the message msg. Waits until a string
is digited and returns it.
- print(s): Shows to the screen the string s
E.g.
n = input(‘Give me a number: ‘)
print(‘Hello World!’)
Print function: Really useful!
The print function is used very often, in particular to debug the code and to show
steps of the program.
The function can take several values, concatenating them using spaces.
The string function s.format(a, b, ...) can be useful combined with print.
It allows to format the string s, let’s see the example.
E.g.
‘hello {name}, this is the accuracy: {acc:.2f}%’.format(name=‘Tony’, acc=0.333333)
‘hello {}, this is the accuracy: {:.2f}%’.format(‘Tony’, 0.333333)
E.g.
empty = [ ]
elems = [1, ‘2’, True, 0, -1, 3 + 5, 4 <= 3]
To access an object of the list, you can use the positional index such as the
strings!
E.g.
elems[1] ‘2’
elems[0:2] [1, ‘2’]
List (2)
We have said that a list can be modified, in fact you can assign a value to a
position, altering the list content. A list can be also an item of another list!
E.g.
elems[0] = ‘ok’
elems[1] = [10, 100, 1000]
It is possible to modify the linear flow of a program using some construct that
basically:
E.g.
x, y = 5, 3
if x < y:
print(‘it is true’)
else:
print(‘it is false’)
It is also possible to omit the clause else, executing the code only if it is true.
E.g.
x, y, z = 3, 4, 5
if x <= y:
print(‘x less or equal to y’)
elif z > x:
print(‘z is also greater than y’)
For
The for loop is one of the two ways to repeat a block of instructions. It can be
useful to iterate over a set of objects or to count.
E.g.
for i in range(10):
print(i)
- range(stop)
- range(start, stop [, step])
E.g.
range(0, 10, 2) # 0, 2, 4, 6, 8, 10
range(5) # 0, 1, 2, 3, 4, 5
While
The while loop is the second method to loop over a set of instructions. The
instructions are executed until the boolean condition it False.
E.g.
i=0
while i < 10:
print(i)
i += 1
Continue and Break
Other than the common data structure’s functions and operations, a there are
three additional operations:
- union, using | (pipe)
- intersection, using &
- difference, using - (minus)
- symmetric difference, using ^
Dictionary (1)
A dictionary is pretty different from the previous data structures, because it
contains key-value elements.
The elements can be accessed (and modified) only by the key, not by position.
E.g.
d[‘ok’] 3
d[‘a’] = 2 # if the key ‘a’ is in d, it is modified, else it added to the dictionary.
You can have access to the keys and values of a dictionary d, using the relative
functions d.keys() and d.values()
Dictionary (2)
Looping over a dictionary implies iterating over the keys.
E.g.
d = {‘a’: 1, ‘b’: 2, ‘c’:3}
for k in d:
print(k, d[k])
Iterating over the key-value pairs is possible through the function items().
E.g.
for k, v in d.items():
print(k, v)
zip() function
The zip() function can be useful if you have two lists that you want to iterate
simultaneously.
E.g.
Let’s see how to implement the function max, between numbers a and b.
The functions can have lots of parameters (e.g. plotting functions) or can have
parameters used very often.
A variable defined inside a function body is defined local (to that function).
In Python there are 2 keywords that allow to change the scope of the variables:
- global var: the variable var considered inside the scope is the global one.
- nonlocal var: the variable var considered inside the scope is the one of the
outer scope.
Lambda functions
Sometimes is useful to declare functions “on the fly”, usually used only once and
without a long definition.
E.g.
def times2(a):
return a * 2
this function can be written using the lambda keyword: lambda n1, n2, … : <body>