SLIDES 1 Escp - Python - Ds - 2020
SLIDES 1 Escp - Python - Ds - 2020
• Used by:
– Google, Yahoo!, Youtube
– Many Linux distributions
– Games and apps (e.g. Eve Online)
2
Philosophy of Python
import this
3
Python is used everywhere!
4
Interpreted Languages
• Interpreted
– Not compiled like Java
– Code is written and then directly executed by an interpreter
– Type commands into interpreter and see immediate results
Java: Runtime
Code Compiler Computer
Environment
5
Installing Python
Windows: Mac OS X:
• Download Python from http:// • A Python version is already
www.python.org installed.
• Install Python. • Open a terminal and run
• Run Idle from the Start Menu. python or run Idle from
Finder.
You should install some commonly used ML • You might want to update your
lib: python
• numpy: for any work with matrices,
especially math operations
• scipy: scientific and technical computing Linux:
• pandas: data handling, manipulation, and • Chances are you already have
analysis Python installed. To check, run
• matplotlib: data visualisation python from the terminal.
• scikit learn: machine learning
pip3 install requests beautifulsoup4 • If not, install from your
distribution's package system. 6
Our First Python Program
• Python does not have a main method like Java
– The program's main code is just written directly in the file
• Python statements do not end with semicolons
hello.py
1 print("Hello, world!")
7
Python Basics
Interactive Interpreter
Comments
Variables and Types
Numbers and Booleans
Strings and Lists
Console I/O
Control Flow
Loops
Functions
8
Interactive Interpreter
9
Comments
# Single line comments start with a ‘#'
"""
Multiline comments can be written between
three "s and are often used as function
and module comments.
"""
10
Variables
x = 3
x*8 No semicolon!
# => 24
11
Type
Variables in Python are dynamically-typed:
declared without an explicit type
However, objects have a type, so Python knows
the type of a variable, even if you don't
type(1) # => <class 'int'>
type("Hello") # => <class 'str'>
type(None) # => <class 'NoneType'>
12
Numbers
3 # => 3 (int)
3.0 # => 3.0 (float)
1+1 #=>2
9-2 #=>7
5*4 # => 20
5/2 # => 2.5
13/4 # => 3.25
9/3 # => 3.0
7/1.4 # => 5.0
7//3 # => 2 (integer division)
7%3 # => 1 (integer modulus)
2**5 # => 32 (exponentiation)
13
Booleans
True # => True
False # => False
not True # => False
True and False # => False
True or False # => True
1 == 1 # => True
2 * 3 == 5 # => False
1 != 1 # => False
2 * 3 != 5 # => True
1 < 10 # => True
1<2<3 # => True
1 < 2 >= 3 # => False
14
String
Both ' and " create string literals
a = “Hello"
a + ' ' + “world" + "!" # Hello world!
Indexing from 0 or negative indexing from -1; Ex. s = “ILOVEESCP"
s[0] == ‘I’
s[8] == ‘P’
len(s) == 9
s[-1] == ???
s[:2] == ??? # slicing
s[-2:] == ???
s[:5:2] == ???
s[4::-2] == ???
15
List
16
Dictionary
17
Set: Unordered collection of distinct hashable elements
empty_set = set()
set_from_list = set([1, 2, 1, 4, 3]) # => {1, 3, 4, 2}
a = set("mississippi") # {'i', 'm', 'p', 's'}
a.add('r')
a.remove('m') # raises KeyError if 'm' is not present
a.discard('x') # same as remove, except no error
a.clear()
a = set("abracadabra") # {'a', 'r', 'b', 'c', 'd'}
b = set("alacazam") # {'a', 'm', 'c', 'l', 'z'}
a-b # =>{'r','d','b'}
# Union
a | b # => {'a', 'c', 'r', 'd', 'b', 'm', 'z', 'l'}
# Intersection
a&b #=>{'a','c'}
18
Whitespace Significance
• Python uses indentation to indicate blocks, instead of {}
– Makes the code simpler and more readable
– In Java, indenting is optional. In Python, you must indent.
– You may use either tabs or spaces, but you must be consistent
hello3.py
1 # Prints a welcoming message.
2 def hello():
3 print("Hello, world!")
4 print("How are you?")
5
6 # main (calls hello twice)
7 hello()
8 hello()
19
Control flow: if/else
if some_condition:
print("Some condition holds")
elif other_condition:
print("Other condition holds")
else:
print("Neither condition holds”)
20
For loops
Loops through a block of code a number of times
n = 10
for i in range(10):
print(i)
for ch in "ESCP":
print(ch)
21
while loops
Loops through a block of code while a specified condition is met
22
break and continue
# break breaks out of the smallest enclosing for or while loop
23
Functions
• Function: A function is a block of code designed to perform
a particular task.
hello2.py
• Syntax: # Prints a helpful message.
1
def name(): 2 def hello():
3 print("Hello, world!")
statement 4
5 # main (calls hello twice)
statement 6 hello()
... 7 hello()
statement
25
Function
# product accepts any number of arguments
def product(*nums, scale=1):
p = scale
for n in nums:
p *= n
return p
num = [1,2,3,4,5]
product(*num)
26
Exercise
• Write a function to check if an element is in a list
• Write a function to check if a string is a palindrome or not (a
palindrome number is a number which is equal to its
reverse)
• Create a function that determines if a positive integer
number is a prime number or not (a prime number is a
natural number greater than 1 that has no positive divisors
other than 1 and itself).
• Write a function to print all prime numbers from 1 to n
27
Functional Programming
f(x)
A lambda function is a small anonymous function.
A lambda function can take any number of arguments, but can only have one
expression.
Examples:
x = lambda a : a + 10
print(x(5))
x = lambda a, b, c : a + b + c
print(x(5, 6, 2))
28
Functional Programming Concepts
29
Functional Programming
def myfunc(n):
return lambda a : a * n
mydoubler = myfunc(2)
mytripler = myfunc(3)
print(mydoubler(11))
print(mytripler(11))
30
Exercise
31
Generators
Resumable Functions
def generate_ints(n):
for i in range(n):
yield i
Regular Functions
Return a single, computed value
Generators
Return an iterator that will generate a stream of values
32
Why generator?
33
Class
Python is an object oriented programming language.
Almost everything in Python is an object, with its properties and methods.
A Class is like an object constructor
Syntax:
class ClassName:
<statement>
<statement>
<statement>
x = Myclass()
print(x.p)
34
Class
Custom Constructor using __init__
class MyOtherClass:
num = 12345
def __init__(self, num=0):
self.num = num
x = MyOtherClass()
print(x.num)
y = MyOtherClass(5)
print(y.num)
del x.num
print(x.num)
35
Class
class Dog:
kind = 'Canine'# class variable shared by all instances
def __init__(self, name):
self.name = name # instance variable unique to each instance
a = Dog('Astro')
b = Dog('Buddy')
a.kind # 'Canine' (shared by all dogs)
b.kind # 'Canine' (shared by all dogs)
36
Handling Exceptions
def read_int():
"""Read an integer from the user."""
return int(input("Please enter a number: "))
return x
37
Exercise
38
Files IO
#Read text
f = open('../Dropbox/helloworld.txt','r')
message = f.read()
print(message)
f.close()
#Read lines
f = open('../Dropbox/helloworld.txt','r')
message = f.readlines() #List
print(message)
f.close()
#Without closing
with open('../Dropbox/helloworld.txt','r') as f:
message = f.readlines() #List
39
Files IO
#Example with write
file = open(‘../Dropbox/testfile.txt', 'w')
file.write('Linea 1\n')
file.write('Linea 2\n')
file.close()
#re-write
file = open(‘../Dropbox/testfile.txt', 'w')
file.write('Linea 3\n')
file.close()
#append
file = open(‘../Dropbox/testfile.txt', 'a')
file.write('Linea 4\n')
file.close()
#with
with open('../Dropbox/testfile.txt','a') as f:
f.write('Linea 5\n')
40
Exercise
• Create a script that reads input.txt file, which
contains a number in each line.
• Sum all numbers and write the result in file
output.txt
• Write lines with characters that are not
numbers in a different file called errors.txt
41
Numpy
NumPy (short for Numerical Python) provides an
efficient interface to store and operate on dense
data buffers:
• Efficient storage
• Data operations
42
Numpy
#Creating Arrays from Python Lists
array1 = np.array([1, 4, 2, 5, 3])
array2 = np.array([3.14, 4, 2, 3])
array3 = np.array([[1,2,3],[4,5,6]])
array4 = np.array([1, 2, 3, 4], dtype=‘float32’)
a = np.zeros((2,2)) # Array of all zeros
b = np.ones((1,2)) # Array of all ones
43
Numpy
np.random.seed(0) # seed for reproducibility
x1 = np.random.randint(10, size=6) # One-dimensional array
x2 = np.random.randint(10, size=(3, 4)) # 2-dimensional array
x3 = np.random.randint(10, size=(3, 4, 5)) # 3-dimensional ar.
44
Numpy
Indexing of arrays:
x[start:stop:step]
#Multi dimentional
x2
x2[:2, :3] # two rows, three column
x2[:3, ::2] # all rows, every other column
x2[0, :] # first row of x2
x2[0, :]
x2_sub_copy = x2[:2, :2].copy()
z = np.concatenate([x, y]) #concatenate
z = np.hstack([x, y]) #hstack
z = np.vstack([x, y]) #vstack
45
Operations
46
Pandas
• Python Data Analysis Library (pandas) is an open source
BSD-licensed library providing high-performance, easy-
to-use data structures and data analysis tools for the
Python programming language
47
Pandas
#Create an Empty DataFrame
import pandas as pd
df = pd.DataFrame()
print(df)
48
Pandas
• Read CSV into a DataFrame object
#Read csv
import pandas as pd
df = pd.read_csv(‘./movies.csv’, sep=',')
#Rename a column
df.rename(columns={'movieId': 'Id', 'title': ‘title'}, inplace=True)
#Column deletion
del movies[‘Id’]
• Iterate over a DataFrame
for index, row in df.iterrows() :
print(row['title'], row[‘genres'])
# Write to a csv file
df.to_csv(‘../moviesFinal.csv', sep=',')
49
Exercise
1. Download cvs file from titanic_train dataset (
2. Read cvs file into DataFrame and call it titanic_train
3. Rename column 'name' to 'Nom'.
4. Upper case 'Nom' column.
5. Select rows from index 200 to 300 into a new
DataFrame
6. Select columns 'PassengerId', 'Nom', 'Survived' from
last DataFrame into a new one.
7. Save final DataFrame as result.csv
50