Sie sind auf Seite 1von 52

Python Crash Course

2019

Lesson 1
Giovanni Trappolini
Francesco Palini
Schedule

- 16 September 2019: 09:00 - 17:00 (Aula 14 B, Building CU007)


- 17 September 2019: 09:00 - 17:00 (Aula 13, Building CU007)
- 19 September 2019: 14:00 - 18:00 (Aula 13, Building CU007)
- 20 September 2019: 09:00 - 13:00 (Aula 14 B, Building CU007)
Contacts

For any question, suggestion or comment, please contact us:

- giovanni.trappolini@uniroma1.it

- francesco.palini@uniroma1.it
Introduction

Welcome to the Programming World!

In this lesson we will learn:

- What is a programming language


- Why choosing Python
- How to setup the environment
- Python Basics
What is a Programming Language

A programming language is a language used by humans to talk with machines.

This language is then translated into binary code,


the only language that the machines understand.
The Art of Programming

The person who writes code is usually called programmer or developer.

The code is a sequence of instructions executed sequentially by the machine, for


this reason is also called procedure, or more commonly, algorithm or program.
Why choose Python? (1)

- Lots of packages
- Simple
- Readable
- Easy to learn
- Lots of support
- Portable
- Free!
Why choose Python? (2)

“Hello World” in Java

public class HelloWorld {


public static void main(String[] args) {
System.out.println(“Hello World”);
}
}
Why choose Python? (3)

“Hello World” in C++

#include <iostream>
using namespace std;

int main() {
count << “Hello World!” << endl;
}
Why choose Python? (4)

“Hello World” in Python

print(“Hello World!”)
Python’s toolset

All we need to program using Python is Anaconda, a free distribution of Python


and R programming languages, for scientific computing...Wonderful!!
Anaconda

The distribution installs:

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

- highlights the syntax


- completes variables and functions names
- warns about syntax errors
- supports the debug of the code

This type of editor is called IDE (Integrated Development Environment). We will


use Spyder as IDE, but for more advanced applications is suggested the use of
PyCharm ( the Professional version is free for students! ;) )
Jupyter

Usually, when you run a program and you want to obtain a result (or output).

Sometimes (often, in Data Science) it is also important to visualize and describe


the steps used to accomplish the result.

Jupyter is the right tool to accomplish this task.


It allows to write (and execute) code, text,
formulas and visualize images or tables.
GitHub

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.

We will see later in this course how to use these tools


Let’s Setup!
Links:
- Apps:
- Anaconda
- Git
- GitKraken
- Sites:
- GitHub Education
- Python Tutor
- Python Documentation
Let’s start learning Python!
Python Basics
- Interactive Interpreter
- Comments
- Variables and Types
- Numbers
- Booleans
- Strings
- Lists
- Console I/O
- Control flow: if-else, for, while
- Tuples, Sets, Dictionaries
- Functions
Python Interpreter

The Python interpreter is a tool which reads and execute Python code line-by-line
in an interactive way.

You can access to the


interpreter opening
Anaconda Prompt and
writing python or ipython
(a boosted version of the
interpreter)
Comments

There are two ways to add comment to the program:

- Using # it is possible to add a line comment


- Using ‘’’comment here‘’’ you can add a multiline comment. This syntax is also
used to add code documentation, writing the comment as the first
instruction into a class or function definition
Variables

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

There are 2 numeric types:

- Integers (int): 5, 3, -1, 6, 5 + 3, …


- Floats (float): 6.0, -1.4, 0.0404, …

In Python 3, the division operator / returns always a float value. You can obtain
an integer division result with the operator //.
Booleans

Boolean (bool) is a subtype of int:

- 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

- len(s): returns the number of characters in s


- s.startswith(a): returns True if s starts with the string a, False otherwise
- s.endswith(a): returns True if s ends with the string a, False otherwise
- s.find(a): returns the index of the string a in s. Returns -1 if it is absent
- s.islower(): returns True if s is lowercase, False otherwise
- s.replace(a, b): returns s with the occurrences of a in s, replaced by b
- s.split(a): splits the string s using as separator a. It returns the list of words.
If the separator is not specified, it is used the whitespace.
- s.join(list): the reverse of split. It joins the elements of list using s as
“connector”. It returns a string
Basics of I/O (Input/Output)

Two fundamental 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)

Result: ‘hello Tony, this is the accuracy: 0.33%’


List (1)
A list is an objects container. It can contain different types of objects and the
content can be modified.

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]

Do you remember the strings feature for multiplication and sum?


The same is valid for lists: elems * 3 and elems + elems
List Functions

- len(l): returns the number of elements in l


- l.append(a): adds element a at the end of the list l
- l.insert(i, a): adds the element a in position i
- l.remove(a): removes the first occurrence of the element a
- l.index(a): returns the first index of the element a
- l.pop(a): removes and returns the element at index a
- l.reverse(): returns a reversed copy of l
- l.sort(): returns a sorted copy of l
- max(l): returns the maximum value in l
Control Flow

It is possible to modify the linear flow of a program using some construct that
basically:

1. Condition the execution in respect to a boolean expression


2. Loops over the same group of instructions
If-else (1)
The construct if-else can be useful to create a branch into the code. According to
the evaluation of a boolean condition.

E.g.
x, y = 5, 3
if x < y:
print(‘it is true’)
else:
print(‘it is false’)

Indentation counts!! There are no { }, Python uses indentation to distinguish


blocks of instructions!
If-else (2)

It is also possible to omit the clause else, executing the code only if it is true.

Since if-else is a instruction as well, it is allowed to concatenate them. In Python


there exists the keyword elif, equivalent to else if.

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)

for el in [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]:


print(el)
range() function

The range function generates a “sequence” of numbers.

There are 2 ways of calling the function:

- 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

The keywords are used to interrupt the execution inside a loop:

- continue: stops the current iteration inside the loop


- break: stops the entire execution of the loop

for w in [‘try’, ‘this’, ‘moto’]:


if w == ‘this’:
break
Data Structures

- List: A collection of mutable and indexed objects. We already know them.


- Tuple: A collection of immutable and indexed objects.
- Set: A collection of immutable and unique objects. It is not indexed.
- Dictionary: A collection of key-value pairs. The keys are unique.

Note about strings:


String objects are similar to Tuple objects, because are immutable and indexed.
It is possible to access single characters or substrings, in the same way we have
seen for lists.
Tuple

A tuple can be defined in this way: t = (1, ‘ok’, -1.0)

As we said, a tuple item can be accessed by position, as for the lists.

However, if you try to modify an element an error is returned:


TypeError: 'tuple' object does not support item assignment
Set

A set can be defined in this way: s = {1, 2, 3, 2, 1}

In this example, since a set contains only unique values, s = {1, 2, 3}

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.

An example of dictionary is: d = {‘ok’: 3, 5: 3, -5: [1, 2, 3]}

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.

students = [‘Marco’, ‘Sebastian’, ‘John’]

ages = [24, 19, 45]

for student, age in zip(students, ages)):


print(student, age)
Functions (1)
A function can be defined using the keyword def.

Let’s see how to implement the function max, between numbers a and b.

def myMax(a, b):


if a < b:
return b
else:
return a

The variables a and b are called parameters. It is possible to create a function


without parameters, but the parenthesis are mandatory.
Functions - Default parameters

The functions can have lots of parameters (e.g. plotting functions) or can have
parameters used very often.

In this case is common to use default parameters.

E.g. Let’s implement a power of n function with default value of n=2.

def power(b, n=2):


return b ** n
Scope Resolution

Rule of Thumb: Nearest first!


How to manage the scope?

A variable defined in the main body of a file or interpreter is defined global.

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>

i.e. times2 = lambda a: a * 2

Das könnte Ihnen auch gefallen