100% found this document useful (1 vote)
95 views

SLIDES 1 Escp - Python - Ds - 2020

The document provides an overview of the Python programming language. It discusses that Python was created in 1991 and is commonly used as a scripting language for small to medium sized projects. It also mentions some common uses of Python including at Google, Yahoo!, YouTube and many Linux distributions. The document then covers Python's interpreted nature, how to install Python on different operating systems, basic Python concepts like variables, data types, control flow and functions.

Uploaded by

N
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (1 vote)
95 views

SLIDES 1 Escp - Python - Ds - 2020

The document provides an overview of the Python programming language. It discusses that Python was created in 1991 and is commonly used as a scripting language for small to medium sized projects. It also mentions some common uses of Python including at Google, Yahoo!, YouTube and many Linux distributions. The document then covers Python's interpreted nature, how to install Python on different operating systems, basic Python concepts like variables, data types, control flow and functions.

Uploaded by

N
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 50

Intro

Slides adapted from http://cs231n.github.io/


python-numpy-tutorial/, S.Hatcher, B. Beebe,
S.Geluso, S. Redmond, and others.
Python!
• Created in 1991 by Guido van Rossum (now at Google)
– Named for Monty Python

• Useful as a scripting language


– script: A small program meant for one-time use
– Targeted towards small to medium sized projects

• 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

Python: Code Interpreter Computer

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

You can write python code right here!!!!

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

x = "Hello, I'm "


x += "Python!" What happened here?

# => "Hello, I'm Python"

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

Nb: else is optional

20
For loops
Loops through a block of code a number of times
n = 10
for i in range(10):
print(i)

for item in iterable:


process(item)

for ch in "ESCP":
print(ch)

# Loop over elements of a list.


for number in [3, 1, 4, 1, 5]:
print(number ** 2, end=‘|')

21
while loops
Loops through a block of code while a specified condition is met

# Print powers of three below 10000


n=1
while n < 10000:
print(n)
n *= 3

22
break and continue
# break breaks out of the smallest enclosing for or while loop

for n in range(2, 10):


if n == 5:
break
print(n, end=', ‘)

# continue continues with the next iteration of the loop

for letter in "PSGMU":


if letter in "SG":
continue
print(letter, end=‘*')

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

– Must be declared above the 'main' code


– Statements inside the function must be indented
24
Function

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)

A very good example is format function of string


str.format(*args, **kwargs)
"{0}{b}{1}{a}{0}{2}".format(5, 8, 9, a='z', b='x')
# => 5x8z59
Here: args = (5, 8, 9)
kwargs = {'a':'z', 'b':'x'}

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.

Syntax: lambda arguments : expression


=> The expression is executed and the result is returned

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

Primary entity is a “function"


"Pure" functions are mathematical
Output depends only on input
No side effects that modify internal state

29
Functional Programming
def myfunc(n):
return lambda a : a * n
mydoubler = myfunc(2)
mytripler = myfunc(3)
print(mydoubler(11))
print(mytripler(11))

More examples: Map/filter


Map: applies a function to all the items in an input_list
map(function_to_apply, list_of_inputs)
Example:
items = [1, 2, 3, 4, 5]
squared = list(map(lambda x: x**2, items))
Filter: creates a list of elements for which a function returns true
number_list = range(-5, 5)
less_than_zero = list(filter(lambda x: x < 0, number_list))
print(less_than_zero)

30
Exercise

Write a function/piece of code to calculate


the length of each element in a list of string.
Ex: [“I love”, “ECSP”, “and”, “Math”]

Write a function to return a list of even


numbers from a given list of integers.
[1,3,5,8,9,12,13] => [8,12]

31
Generators
Resumable Functions
def generate_ints(n):
for i in range(n):
yield i

g = generate_ints(3) # Doesn't start the function!


type(g) # => <class 'generator'>
next(g) # => 0
next(g) # => 1

Regular Functions
Return a single, computed value
Generators
Return an iterator that will generate a stream of values

32
Why generator?

• Compute data on demand


• Reduces in-memory buffering
• Avoid expensive function calls
• Describe (finite or infinite) streams of
data

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>

Defining a class == creating a class object (like int, str)


Defining a class != instantiating a class
For example:
class Myclass:
p=5

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)

a.name # 'Astro' (unique to a)


b.name # 'Buddy' (unique to b)

36
Handling Exceptions
def read_int():
"""Read an integer from the user."""
return int(input("Please enter a number: "))

What happens if the user enters a nonnumeric input?


def read_int():
"""Read an integer from the user (better).""" Handling Exceptions
while True:
try: try:
x = int(input("Please enter a number: ")) dangerous_code()
break except SomeError:
except ValueError: handle_the_error()
print("Oops! Invalid input. Try again...")

return x

37
Exercise

Write a rectangle class with a


method called get_area() to
return the area of a rectangle
given its width and height

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

# => NP array contains the same type

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.

print("x3 ndim: ", x3.ndim)


print("x3 shape:", x3.shape)
print("x3 size: ", x3.size)

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

• DataFrames are essentially multidimensional arrays with


attached row and column labels, and often with
heterogeneous types and/or missing data. You can think
of it as a spreadsheet data representation.

47
Pandas
#Create an Empty DataFrame
import pandas as pd
df = pd.DataFrame()
print(df)

#Create a DataFrame from Lists


data = [1,2,3,4,5]
df = pd.DataFrame(data)
print(df)

dataFrutas = [[‘Manzana',100], [‘Pera',105], ['Banano',130]]


df = pd.DataFrame(dataFrutas, columns=[‘Nombre', 'Peso(gr)'])
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

You might also like