SlideShare a Scribd company logo
Python IntroductionEnrico Franchi (efranchi@ce.unipr.it)
We will perhaps eventually be writing only small
modules that are identified by name as they are used
to build larger ones, so that devices like indentation,
rather than delimiters, might become feasible for
expressing local structure in the source language.
Modules (identified by name and composed)
Indentation to express local structure
2
Donald E. Knuth,
Structured Programming with go to Statements, 1974
1989
Started
Im
plem
entation1991
FirstPublicVersion
1994
StableRelease
2000
Python
2.0
2003
Python
2.3
2008
Python
3.0
Python Timeline
3
1989
Started
Im
plem
entation1991
FirstPublicVersion
1994
StableRelease
2000
Python
2.0
2003
Python
2.3
2008
Python
3.0
Python Timeline
3
1991
Started
Im
plem
entation
1995
StableRelease
2000
Java
1.3
2004
Java
1.5
2006
Java
1.6
JAVA
Python 2 vs. 3
In order to greatly improve the language, GvR decided that a
newer major version that could break compatibility was needed
Python 3 was released in 2008 with the idea that the transition
would last at least 7 years (i.e., > 2015)
Now the “standard” version of Python is Python 2.7 (released in
2010). The world is mostly with Python 2.7
Most libraries are now Python 3 compatible and it is possible to
write code that works on both versions
In the future, Python 3 will be the standard
4
Why learning a new language
Because it makes easier to perform some tasks
To land a (better) job
To work with some other software/in some environment
To learn a new way of thinking
5
Language Categories
6
Declarative Imperative
Functional
Haskell, OCaml
Erlang, Lisp, Scheme
Logic
Prolog, Mercury, SQL
Imperative
Pascal, C
Object Oriented
Java, Ruby, C++,
Python, Smalltalk
Hybrid Languages
7
C++ Templates
C++
Object Oriented
Part
C++
Functions
Declarative Imperative
Functional Imperative
Object Oriented
“Functional” C++
8
template <int N>
struct Factorial
{
enum { value = N * Factorial<N - 1>::value };
};
template <>
struct Factorial<0>
{
enum { value = 1 };
};
int main() {
int num = Factorial<4>::value;
return 0;
}
fun fact 0 = 1
| fact n = n * fact (n - 1)
SML
f (n) =
1 n = 0
n⋅ f (n −1) otherwise
⎧
⎨
⎩
More “functional” C++
9
#include <iostream>
#include <algorithm>
#include <iterator>
#include <vector>
#include <functional>
int op_increase (int i) { return ++i; }
int main () {
const int foo[] = {10, 20, 30, 40, 50};
const size_t foo_size = sizeof(foo)/sizeof(int);
std::vector<int> bar(foo_size);
std::transform (foo, foo+foo_size, bar.begin(), op_increase);
// bar: 11 21 31 41 51
std::copy(bar.begin(), bar.end(),
std::ostream_iterator<int>(std::cout, ", "));
return 0;
}
Python
10
Python
Functional
Imperative
Object Oriented
“Functional” parts
of Python come
from the true
“everything is an
object” philosophy
Everything is an Object
In Python everything is an object
Values, Instances, Functions, ... even classes
11
def fact(n):
# I hate naive factorials
if n == 0:
return 1
else:
return n * fact(n-1)
alias_for_fact = fact
values = map(fact, [1, 2, 3, 4])
print values
# [1, 2, 6, 24]
class Person(object):
def __init__(self, name):
self.name = name
crew = map(Person, ["Malcom Reynolds", "Zoe Washburne",
"Kaylee Frye", "Jayne Cobb",
'Hoban "Wash" Washburne'])
Dynamic Typing Static Typing
Python, Ruby Haskell, SML, Java, (C++)
Perl, Javascript, PHP, Bash C
Strong
Typing
Weak
Typing
Strong
Typing
Weak
Typing
SM
L
H
askell
Java
C
++
C
Python
Typing
12
CPython
javac
Java Source Code
JVM
Python Source Code
Java Bytecode Python Bytecode
Execution
13
CPython
javac
Java Source Code
JVM
Python Source Code
Java Bytecode Python Bytecode
Execution
13
Interactive Shell
14
A read–eval–print loop (REPL) is
a simple, interactive computer
programming environment
Started with Lisp, most “good”
languages have it (Scala,
Haskell, Ruby, Perl, Scheme, ...)
It is useful to develop
interactively small (and not so
small) bits of code, and
especially to do scientific/
algorithmic computations
Why learning a new language
Because it makes easier to perform some tasks
To land a (better) job
To work with some other software/in some environment
To learn a new way of thinking
15
To learn a new way of thinking...
A language that does not affect the way you think about
programming, is not worth knowing.
Alan Perlis, 1966 Turing Award
16
READABILITY
GvR
Zen of Python
PEP8
Readability Counts
A program is read many
more times than it is
written.
Optimizing for readability
actually makes sense.
Python is built to be
highly readable (semantic
whitespace, low clutter,
no boilerplate)
17
18
>>> import this
The Zen of Python, by Tim Peters
Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!
Why learning a new language
Because it makes easier to perform some tasks
To land a (better) job
To work with some other software/in some environment
To learn a new way of thinking
19
What helps...
Dynamic, High-Level: few lines of code make “lots” of stuff
Often “higher level” than design-patterns: several dp are from trivial
or even more verbose/less general
Almost no boilerplate: write what you mean
Highly readable: people strive to write elegant code
Small but very well thought set of primitive concepts
(Python “time-machine”)
Meta-programming: even higher level of abstraction, minor lines of
code and/or more general solutions (e.g., ORM)
20
... and libraries
But mostly, a simple language encourages developers to
write libraries for various tasks
Lots of academics and companies wrote libraries for
almost every conceivable thing
PyPI (31113 libraries alone, plus all the project not indexed
but in GitHub, Bitbucket, Google Code or Sourceforge)
More on that later...
21
Why learning a new language
Because it makes easier to perform some tasks
To land a (better) job
To work with some other software/in some environment
To learn a new way of thinking
22
Python Community
Pycon US, EuroPython
Pycon.it, Python Italia A.P.S.
Widely used in the open source community: several key
projects are written in Python, and it is a default
component for several Linux distributions
Friendly and supportive community (very good social
capital), some “huge” names are Italians (and can help)
23
24
Python Jobs
Learning new (good) languages is always good, even if you
are not going to use them (remember Perlis)
Python Paradox (see Graham, )
Several companies use Python
And often they are the “right” companies to work with
Job demand higher than job offer
25
Companies
26
ITA Software
Heroku, eBay, Microsoft,
Canonical, Spotify,
RedHat, Amazon, Netflix,
Adroll, Rackspace, Box,
Dropbox, Facebook,
Guidebook, Oracle,
Reddit, ....
Why learning a new language
Because it makes easier to perform some tasks
To land a (better) job
To work with some other software/in some
environment
To learn a new way of thinking
27
Scripting 3rd Party
28
SIMULIA Abaqus FEA
Blender, Cinema 4D,
Lightwave, Houdini, Maya,
modo, MotionBuilder,
Softimage, Nuke, GIMP,
Inkscape, Scribus and Paint
Shop Pro, GNU Debugger,
ArcGIS, QGIS
UNIX
Python Concurrency
Threads (bad solution, as always)
Twisted (asynchronous programming)
gevent (“light” threading for massive concurrency)
multiprocess (yeah, it’s UNIX!)
MPI, CUDA, etc...
29
Python and the Web
Full-stack frameworks (Django, Web2Py, Pylons, ...)
MVC, Component Based
Multi-DB ORM – URL Dispatcher – Templating System
Light-weight frameworks (Flask)
WSGI (simple web-server interface language)
30
Django
One of the most widely used
platform in the world
Pintertest, Instagram,
Washington Post,
ORM, URL Dispatcher, Web
Templating System
Automatic “Admin” generation
from the Model
Automatic translation from web
forms to entities
Built-in internationalization
Buil-in caching system
Extensible (built-in) authentication
system
Auto RSS & Atom generation
Built-in commenting system
Semi-auto Google Sitemap
Generation
Mitigation system for several
security issues (SQL Injection,
Cross-site scripting, ...)
31
Django Example
32
from django.db import models
class Poll(models.Model):
question = models.CharField(max_length=200)
pub_date = models.DateTimeField('date published')
class Choice(models.Model):
poll = models.ForeignKey(Poll)
choice_text = models.CharField(max_length=200)
votes = models.IntegerField(default=0)
>>> Poll.objects.all()
[<Poll: What's up?>]
# Django provides a rich database lookup API that's entirely driven by
# keyword arguments.
>>> Poll.objects.filter(id=1)
[<Poll: What's up?>]
>>> Poll.objects.filter(question__startswith='What')
[<Poll: What's up?>]
Django Admin
33
Flask Hello, World!
34
from flask import Flask
app = Flask(__name__)
@app.route("/")
def hello():
return "Hello World!"
if __name__ == "__main__":
app.run()
Extremely minimal web framework
Minimal memory requirements
Also comes with built-in server
Compact and easy to write
E.g., web interface to a Raspberry PI
HIS EX,
T E M P O
R NUMERIC PYTHON
• Numpy (low-level numerical computations) +
Scipy (lots of additional packages)
• Pandas (R-like)
• IPython (wonderfull command line interpreter) +
IPython Notebook (“Mathematica-like” interactive documents)
• HDF5 (PyTables, H5Py), Databases
• Specific libraries for machine learning, etc.
• General Purpose Object Oriented Programming
TOOLSCU
S E D
TOOLSCU
S E D
TOOLSCU
S E D
DENIQU
E
G U B E R
G R E N
Our Code
Numpy
Atlas/MKL
Improvements
Improvements
Algorithms are
fast because of
highly optimized
C/Fortran code
4 30 LOAD_GLOBAL 1 (dot)
33 LOAD_FAST 0 (a)
36 LOAD_FAST 1 (b)
39 CALL_FUNCTION 2
42 STORE_FAST 2 (c)
NUMPY STACK
c = a · b
ndarray
ndarray
Memory
behavior
shape, stride, flags
(i0, . . . , in 1) ! I
Shape: (d0, …, dn-1)
4x3
An n-dimensional array references some
(usually contiguous memory area)
An n-dimensional array has
property such as its shape or the
data-type of the elements containes
Is an object, so there is some
behavior, e.g., the def. of
__add__ and similar stuff
N-dimensional arrays are homogeneous
(i0, . . . , in 1) ! I
C-contiguousF-contiguous
Shape: (d0, …, dn)
IC =
n 1X
k=0
ik
n 1Y
j=k+1
dj
IF =
n 1X
k=0
ik
k 1Y
j=0
dj
Shape: (d0, …, dk ,…, dn-1)
Shape: (d0, …, dk ,…, dn-1)
IC = i0 · d0 + i14x3
IF = i0 + i1 · d1
ElementLayout
inMemory
Stride
C-contiguous F-contiguous
sF (k) =
k 1Y
j=0
dj
IF =
nX
k=0
ik · sF (k)
sC(k) =
n 1Y
j=k+1
dj
IC =
n 1X
k=0
ik · sC(k)
Stride
C-contiguousF-contiguous
C-contiguous
(s0 = d0, s1 = 1) (s0 = 1, s1 = d1)
IC =
n 1X
k=0
ik
n 1Y
j=k+1
dj IF =
n 1X
k=0
ik
k 1Y
j=0
dj
ndarray
Memory
behavior
shape, stride, flags
ndarray
behavior
shape, stride, flags
View View
View View
Views
C-contiguous
ndarray
behavior
(1,4)
Memory
C-contiguous
ndarray
behavior
(1,4)
Memory
ndarray
Memory
behavior
shape, stride, flags
matrix
Memory
behavior
shape, stride, flags
ndarray
matrix
BasicIndexing
AdvancedIndexing
Broadcasting!
AdvancedIndexing
Broadcasting!
AdvancedIndexing
Broadcasting!
AdvancedIndexing
Broadcasting!
AdvancedIndexing2
AdvancedIndexing2
AdvancedIndexing2
AdvancedIndexing2
AdvancedIndexing2
AdvancedIndexing2
Vectorize!
Don’t use explicit for loops unless you have to!

More Related Content

What's hot

Introduction to Python
Introduction to PythonIntroduction to Python
Introduction to Python
Nowell Strite
 
Basics of python
Basics of pythonBasics of python
Basics of python
SurjeetSinghSurjeetS
 
Python programming | Fundamentals of Python programming
Python programming | Fundamentals of Python programming Python programming | Fundamentals of Python programming
Python programming | Fundamentals of Python programming
KrishnaMildain
 
Python tutorial for beginners - Tib academy
Python tutorial for beginners - Tib academyPython tutorial for beginners - Tib academy
Python tutorial for beginners - Tib academy
TIB Academy
 
Introduction to python
 Introduction to python Introduction to python
Introduction to python
Learnbay Datascience
 
Python Course | Python Programming | Python Tutorial | Python Training | Edureka
Python Course | Python Programming | Python Tutorial | Python Training | EdurekaPython Course | Python Programming | Python Tutorial | Python Training | Edureka
Python Course | Python Programming | Python Tutorial | Python Training | Edureka
Edureka!
 
Python ppt
Python pptPython ppt
Python ppt
Rohit Verma
 
Programming with Python
Programming with PythonProgramming with Python
Programming with Python
Rasan Samarasinghe
 
Python ppt
Python pptPython ppt
Python ppt
Mohita Pandey
 
Phython Programming Language
Phython Programming LanguagePhython Programming Language
Phython Programming Language
R.h. Himel
 
Intro to Python
Intro to PythonIntro to Python
Intro to Python
primeteacher32
 
Introduction to the basics of Python programming (part 1)
Introduction to the basics of Python programming (part 1)Introduction to the basics of Python programming (part 1)
Introduction to the basics of Python programming (part 1)
Pedro Rodrigues
 
Beginning Python Programming
Beginning Python ProgrammingBeginning Python Programming
Beginning Python Programming
St. Petersburg College
 
Python
PythonPython
Python, the Language of Science and Engineering for Engineers
Python, the Language of Science and Engineering for EngineersPython, the Language of Science and Engineering for Engineers
Python, the Language of Science and Engineering for Engineers
Boey Pak Cheong
 
Overview of python 2019
Overview of python 2019Overview of python 2019
Overview of python 2019
Samir Mohanty
 
Python basics
Python basicsPython basics
Python basics
Jyoti shukla
 
Intro to Python Programming Language
Intro to Python Programming LanguageIntro to Python Programming Language
Intro to Python Programming Language
Dipankar Achinta
 
Python Programming Language | Python Classes | Python Tutorial | Python Train...
Python Programming Language | Python Classes | Python Tutorial | Python Train...Python Programming Language | Python Classes | Python Tutorial | Python Train...
Python Programming Language | Python Classes | Python Tutorial | Python Train...
Edureka!
 

What's hot (20)

Introduction to Python
Introduction to PythonIntroduction to Python
Introduction to Python
 
Basics of python
Basics of pythonBasics of python
Basics of python
 
Python programming | Fundamentals of Python programming
Python programming | Fundamentals of Python programming Python programming | Fundamentals of Python programming
Python programming | Fundamentals of Python programming
 
Python tutorial for beginners - Tib academy
Python tutorial for beginners - Tib academyPython tutorial for beginners - Tib academy
Python tutorial for beginners - Tib academy
 
Introduction to python
 Introduction to python Introduction to python
Introduction to python
 
Python Course | Python Programming | Python Tutorial | Python Training | Edureka
Python Course | Python Programming | Python Tutorial | Python Training | EdurekaPython Course | Python Programming | Python Tutorial | Python Training | Edureka
Python Course | Python Programming | Python Tutorial | Python Training | Edureka
 
Python ppt
Python pptPython ppt
Python ppt
 
Programming with Python
Programming with PythonProgramming with Python
Programming with Python
 
Python ppt
Python pptPython ppt
Python ppt
 
Phython Programming Language
Phython Programming LanguagePhython Programming Language
Phython Programming Language
 
Intro to Python
Intro to PythonIntro to Python
Intro to Python
 
Introduction to the basics of Python programming (part 1)
Introduction to the basics of Python programming (part 1)Introduction to the basics of Python programming (part 1)
Introduction to the basics of Python programming (part 1)
 
Beginning Python Programming
Beginning Python ProgrammingBeginning Python Programming
Beginning Python Programming
 
Python Tutorial Part 1
Python Tutorial Part 1Python Tutorial Part 1
Python Tutorial Part 1
 
Python
PythonPython
Python
 
Python, the Language of Science and Engineering for Engineers
Python, the Language of Science and Engineering for EngineersPython, the Language of Science and Engineering for Engineers
Python, the Language of Science and Engineering for Engineers
 
Overview of python 2019
Overview of python 2019Overview of python 2019
Overview of python 2019
 
Python basics
Python basicsPython basics
Python basics
 
Intro to Python Programming Language
Intro to Python Programming LanguageIntro to Python Programming Language
Intro to Python Programming Language
 
Python Programming Language | Python Classes | Python Tutorial | Python Train...
Python Programming Language | Python Classes | Python Tutorial | Python Train...Python Programming Language | Python Classes | Python Tutorial | Python Train...
Python Programming Language | Python Classes | Python Tutorial | Python Train...
 

Similar to Python intro

Python Seminar PPT
Python Seminar PPTPython Seminar PPT
Python Seminar PPT
Shivam Gupta
 
Python
PythonPython
Python
Shivam Gupta
 
python-160403194316.pdf
python-160403194316.pdfpython-160403194316.pdf
python-160403194316.pdf
gmadhu8
 
python into.pptx
python into.pptxpython into.pptx
python into.pptx
Punithavel Ramani
 
Chapter - 1.pptx
Chapter - 1.pptxChapter - 1.pptx
Chapter - 1.pptx
MikialeTesfamariam
 
Python Programming Draft PPT.pptx
Python Programming Draft PPT.pptxPython Programming Draft PPT.pptx
Python Programming Draft PPT.pptx
LakshmiNarayanaReddy48
 
Introduction to python for Beginners
Introduction to python for Beginners Introduction to python for Beginners
Introduction to python for Beginners
Sujith Kumar
 
session5-Getting stated with Python.pdf
session5-Getting stated with Python.pdfsession5-Getting stated with Python.pdf
session5-Getting stated with Python.pdf
AyushDutta32
 
Python Tutorial | Python Programming Language
Python Tutorial | Python Programming LanguagePython Tutorial | Python Programming Language
Python Tutorial | Python Programming Language
anaveenkumar4
 
Python unit1
Python unit1Python unit1
PyCon2022 - Building Python Extensions
PyCon2022 - Building Python ExtensionsPyCon2022 - Building Python Extensions
PyCon2022 - Building Python Extensions
Henry Schreiner
 
REPORT ON AUDIT COURSE PYTHON BY SANA 2.pdf
REPORT ON AUDIT COURSE PYTHON BY SANA 2.pdfREPORT ON AUDIT COURSE PYTHON BY SANA 2.pdf
REPORT ON AUDIT COURSE PYTHON BY SANA 2.pdf
Sana Khan
 
Cmpe202 01 Research
Cmpe202 01 ResearchCmpe202 01 Research
Cmpe202 01 Research
vladimirkorshak
 
Seminar report on python 3 course
Seminar report on python 3 courseSeminar report on python 3 course
Seminar report on python 3 course
HimanshuPanwar38
 
python presntation 2.pptx
python presntation 2.pptxpython presntation 2.pptx
python presntation 2.pptx
Arpittripathi45
 
Python_final_print_batch_II_vision_academy.pdf
Python_final_print_batch_II_vision_academy.pdfPython_final_print_batch_II_vision_academy.pdf
Python_final_print_batch_II_vision_academy.pdf
bhagyashri686896
 
Python_final_print_batch_II_vision_academy (1).pdf
Python_final_print_batch_II_vision_academy (1).pdfPython_final_print_batch_II_vision_academy (1).pdf
Python_final_print_batch_II_vision_academy (1).pdf
rupaliakhute
 
Python_final_print_batch_II_vision_academy.pdf
Python_final_print_batch_II_vision_academy.pdfPython_final_print_batch_II_vision_academy.pdf
Python_final_print_batch_II_vision_academy.pdf
sannykhopade
 
Python_vision_academy notes
Python_vision_academy notes Python_vision_academy notes
Python_vision_academy notes
rajaniraut
 
intro.pptx (1).pdf
intro.pptx (1).pdfintro.pptx (1).pdf
intro.pptx (1).pdf
ANIKULSAIKH
 

Similar to Python intro (20)

Python Seminar PPT
Python Seminar PPTPython Seminar PPT
Python Seminar PPT
 
Python
PythonPython
Python
 
python-160403194316.pdf
python-160403194316.pdfpython-160403194316.pdf
python-160403194316.pdf
 
python into.pptx
python into.pptxpython into.pptx
python into.pptx
 
Chapter - 1.pptx
Chapter - 1.pptxChapter - 1.pptx
Chapter - 1.pptx
 
Python Programming Draft PPT.pptx
Python Programming Draft PPT.pptxPython Programming Draft PPT.pptx
Python Programming Draft PPT.pptx
 
Introduction to python for Beginners
Introduction to python for Beginners Introduction to python for Beginners
Introduction to python for Beginners
 
session5-Getting stated with Python.pdf
session5-Getting stated with Python.pdfsession5-Getting stated with Python.pdf
session5-Getting stated with Python.pdf
 
Python Tutorial | Python Programming Language
Python Tutorial | Python Programming LanguagePython Tutorial | Python Programming Language
Python Tutorial | Python Programming Language
 
Python unit1
Python unit1Python unit1
Python unit1
 
PyCon2022 - Building Python Extensions
PyCon2022 - Building Python ExtensionsPyCon2022 - Building Python Extensions
PyCon2022 - Building Python Extensions
 
REPORT ON AUDIT COURSE PYTHON BY SANA 2.pdf
REPORT ON AUDIT COURSE PYTHON BY SANA 2.pdfREPORT ON AUDIT COURSE PYTHON BY SANA 2.pdf
REPORT ON AUDIT COURSE PYTHON BY SANA 2.pdf
 
Cmpe202 01 Research
Cmpe202 01 ResearchCmpe202 01 Research
Cmpe202 01 Research
 
Seminar report on python 3 course
Seminar report on python 3 courseSeminar report on python 3 course
Seminar report on python 3 course
 
python presntation 2.pptx
python presntation 2.pptxpython presntation 2.pptx
python presntation 2.pptx
 
Python_final_print_batch_II_vision_academy.pdf
Python_final_print_batch_II_vision_academy.pdfPython_final_print_batch_II_vision_academy.pdf
Python_final_print_batch_II_vision_academy.pdf
 
Python_final_print_batch_II_vision_academy (1).pdf
Python_final_print_batch_II_vision_academy (1).pdfPython_final_print_batch_II_vision_academy (1).pdf
Python_final_print_batch_II_vision_academy (1).pdf
 
Python_final_print_batch_II_vision_academy.pdf
Python_final_print_batch_II_vision_academy.pdfPython_final_print_batch_II_vision_academy.pdf
Python_final_print_batch_II_vision_academy.pdf
 
Python_vision_academy notes
Python_vision_academy notes Python_vision_academy notes
Python_vision_academy notes
 
intro.pptx (1).pdf
intro.pptx (1).pdfintro.pptx (1).pdf
intro.pptx (1).pdf
 

More from rik0

Complex and Social Network Analysis in Python
Complex and Social Network Analysis in PythonComplex and Social Network Analysis in Python
Complex and Social Network Analysis in Python
rik0
 
Game theory
Game theoryGame theory
Game theoryrik0
 
Social choice
Social choiceSocial choice
Social choice
rik0
 
Social Network Analysis
Social Network AnalysisSocial Network Analysis
Social Network Analysis
rik0
 
Clojure Interoperability
Clojure InteroperabilityClojure Interoperability
Clojure Interoperability
rik0
 
Pydiomatic
PydiomaticPydiomatic
Pydiomatic
rik0
 
Pycrashcourse4.0 pdfjam
Pycrashcourse4.0 pdfjamPycrashcourse4.0 pdfjam
Pycrashcourse4.0 pdfjam
rik0
 
Twcrashcourse
TwcrashcourseTwcrashcourse
Twcrashcourse
rik0
 
Pyimproved again
Pyimproved againPyimproved again
Pyimproved again
rik0
 
Pycrashcourse3.1
Pycrashcourse3.1Pycrashcourse3.1
Pycrashcourse3.1rik0
 
Pycrashcourse3.0
Pycrashcourse3.0Pycrashcourse3.0
Pycrashcourse3.0rik0
 
Pycrashcourse2.0
Pycrashcourse2.0Pycrashcourse2.0
Pycrashcourse2.0
rik0
 
Pycrashcourse
PycrashcoursePycrashcourse
Pycrashcourse
rik0
 
Pyimproved
PyimprovedPyimproved
Pyimproved
rik0
 

More from rik0 (14)

Complex and Social Network Analysis in Python
Complex and Social Network Analysis in PythonComplex and Social Network Analysis in Python
Complex and Social Network Analysis in Python
 
Game theory
Game theoryGame theory
Game theory
 
Social choice
Social choiceSocial choice
Social choice
 
Social Network Analysis
Social Network AnalysisSocial Network Analysis
Social Network Analysis
 
Clojure Interoperability
Clojure InteroperabilityClojure Interoperability
Clojure Interoperability
 
Pydiomatic
PydiomaticPydiomatic
Pydiomatic
 
Pycrashcourse4.0 pdfjam
Pycrashcourse4.0 pdfjamPycrashcourse4.0 pdfjam
Pycrashcourse4.0 pdfjam
 
Twcrashcourse
TwcrashcourseTwcrashcourse
Twcrashcourse
 
Pyimproved again
Pyimproved againPyimproved again
Pyimproved again
 
Pycrashcourse3.1
Pycrashcourse3.1Pycrashcourse3.1
Pycrashcourse3.1
 
Pycrashcourse3.0
Pycrashcourse3.0Pycrashcourse3.0
Pycrashcourse3.0
 
Pycrashcourse2.0
Pycrashcourse2.0Pycrashcourse2.0
Pycrashcourse2.0
 
Pycrashcourse
PycrashcoursePycrashcourse
Pycrashcourse
 
Pyimproved
PyimprovedPyimproved
Pyimproved
 

Recently uploaded

AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
Product School
 
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdfFIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance
 
Essentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with ParametersEssentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with Parameters
Safe Software
 
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Product School
 
UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3
DianaGray10
 
The Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and SalesThe Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and Sales
Laura Byrne
 
Knowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and backKnowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and back
Elena Simperl
 
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdfFIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance
 
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
James Anderson
 
JMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and GrafanaJMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and Grafana
RTTS
 
The Future of Platform Engineering
The Future of Platform EngineeringThe Future of Platform Engineering
The Future of Platform Engineering
Jemma Hussein Allen
 
Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...
Product School
 
Key Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdfKey Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdf
Cheryl Hung
 
"Impact of front-end architecture on development cost", Viktor Turskyi
"Impact of front-end architecture on development cost", Viktor Turskyi"Impact of front-end architecture on development cost", Viktor Turskyi
"Impact of front-end architecture on development cost", Viktor Turskyi
Fwdays
 
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Thierry Lestable
 
ODC, Data Fabric and Architecture User Group
ODC, Data Fabric and Architecture User GroupODC, Data Fabric and Architecture User Group
ODC, Data Fabric and Architecture User Group
CatarinaPereira64715
 
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
Product School
 
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
Product School
 
UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4
DianaGray10
 
FIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdfFIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance
 

Recently uploaded (20)

AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
 
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdfFIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
 
Essentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with ParametersEssentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with Parameters
 
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
 
UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3
 
The Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and SalesThe Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and Sales
 
Knowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and backKnowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and back
 
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdfFIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
 
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
 
JMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and GrafanaJMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and Grafana
 
The Future of Platform Engineering
The Future of Platform EngineeringThe Future of Platform Engineering
The Future of Platform Engineering
 
Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...
 
Key Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdfKey Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdf
 
"Impact of front-end architecture on development cost", Viktor Turskyi
"Impact of front-end architecture on development cost", Viktor Turskyi"Impact of front-end architecture on development cost", Viktor Turskyi
"Impact of front-end architecture on development cost", Viktor Turskyi
 
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
 
ODC, Data Fabric and Architecture User Group
ODC, Data Fabric and Architecture User GroupODC, Data Fabric and Architecture User Group
ODC, Data Fabric and Architecture User Group
 
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
 
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
 
UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4
 
FIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdfFIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdf
 

Python intro

  • 1. Python IntroductionEnrico Franchi (efranchi@ce.unipr.it)
  • 2. We will perhaps eventually be writing only small modules that are identified by name as they are used to build larger ones, so that devices like indentation, rather than delimiters, might become feasible for expressing local structure in the source language. Modules (identified by name and composed) Indentation to express local structure 2 Donald E. Knuth, Structured Programming with go to Statements, 1974
  • 5. Python 2 vs. 3 In order to greatly improve the language, GvR decided that a newer major version that could break compatibility was needed Python 3 was released in 2008 with the idea that the transition would last at least 7 years (i.e., > 2015) Now the “standard” version of Python is Python 2.7 (released in 2010). The world is mostly with Python 2.7 Most libraries are now Python 3 compatible and it is possible to write code that works on both versions In the future, Python 3 will be the standard 4
  • 6. Why learning a new language Because it makes easier to perform some tasks To land a (better) job To work with some other software/in some environment To learn a new way of thinking 5
  • 7. Language Categories 6 Declarative Imperative Functional Haskell, OCaml Erlang, Lisp, Scheme Logic Prolog, Mercury, SQL Imperative Pascal, C Object Oriented Java, Ruby, C++, Python, Smalltalk
  • 8. Hybrid Languages 7 C++ Templates C++ Object Oriented Part C++ Functions Declarative Imperative Functional Imperative Object Oriented
  • 9. “Functional” C++ 8 template <int N> struct Factorial { enum { value = N * Factorial<N - 1>::value }; }; template <> struct Factorial<0> { enum { value = 1 }; }; int main() { int num = Factorial<4>::value; return 0; } fun fact 0 = 1 | fact n = n * fact (n - 1) SML f (n) = 1 n = 0 n⋅ f (n −1) otherwise ⎧ ⎨ ⎩
  • 10. More “functional” C++ 9 #include <iostream> #include <algorithm> #include <iterator> #include <vector> #include <functional> int op_increase (int i) { return ++i; } int main () { const int foo[] = {10, 20, 30, 40, 50}; const size_t foo_size = sizeof(foo)/sizeof(int); std::vector<int> bar(foo_size); std::transform (foo, foo+foo_size, bar.begin(), op_increase); // bar: 11 21 31 41 51 std::copy(bar.begin(), bar.end(), std::ostream_iterator<int>(std::cout, ", ")); return 0; }
  • 11. Python 10 Python Functional Imperative Object Oriented “Functional” parts of Python come from the true “everything is an object” philosophy
  • 12. Everything is an Object In Python everything is an object Values, Instances, Functions, ... even classes 11 def fact(n): # I hate naive factorials if n == 0: return 1 else: return n * fact(n-1) alias_for_fact = fact values = map(fact, [1, 2, 3, 4]) print values # [1, 2, 6, 24] class Person(object): def __init__(self, name): self.name = name crew = map(Person, ["Malcom Reynolds", "Zoe Washburne", "Kaylee Frye", "Jayne Cobb", 'Hoban "Wash" Washburne'])
  • 13. Dynamic Typing Static Typing Python, Ruby Haskell, SML, Java, (C++) Perl, Javascript, PHP, Bash C Strong Typing Weak Typing Strong Typing Weak Typing SM L H askell Java C ++ C Python Typing 12
  • 14. CPython javac Java Source Code JVM Python Source Code Java Bytecode Python Bytecode Execution 13
  • 15. CPython javac Java Source Code JVM Python Source Code Java Bytecode Python Bytecode Execution 13
  • 16. Interactive Shell 14 A read–eval–print loop (REPL) is a simple, interactive computer programming environment Started with Lisp, most “good” languages have it (Scala, Haskell, Ruby, Perl, Scheme, ...) It is useful to develop interactively small (and not so small) bits of code, and especially to do scientific/ algorithmic computations
  • 17. Why learning a new language Because it makes easier to perform some tasks To land a (better) job To work with some other software/in some environment To learn a new way of thinking 15
  • 18. To learn a new way of thinking... A language that does not affect the way you think about programming, is not worth knowing. Alan Perlis, 1966 Turing Award 16
  • 19. READABILITY GvR Zen of Python PEP8 Readability Counts A program is read many more times than it is written. Optimizing for readability actually makes sense. Python is built to be highly readable (semantic whitespace, low clutter, no boilerplate) 17
  • 20. 18 >>> import this The Zen of Python, by Tim Peters Beautiful is better than ugly. Explicit is better than implicit. Simple is better than complex. Complex is better than complicated. Flat is better than nested. Sparse is better than dense. Readability counts. Special cases aren't special enough to break the rules. Although practicality beats purity. Errors should never pass silently. Unless explicitly silenced. In the face of ambiguity, refuse the temptation to guess. There should be one-- and preferably only one --obvious way to do it. Although that way may not be obvious at first unless you're Dutch. Now is better than never. Although never is often better than *right* now. If the implementation is hard to explain, it's a bad idea. If the implementation is easy to explain, it may be a good idea. Namespaces are one honking great idea -- let's do more of those!
  • 21. Why learning a new language Because it makes easier to perform some tasks To land a (better) job To work with some other software/in some environment To learn a new way of thinking 19
  • 22. What helps... Dynamic, High-Level: few lines of code make “lots” of stuff Often “higher level” than design-patterns: several dp are from trivial or even more verbose/less general Almost no boilerplate: write what you mean Highly readable: people strive to write elegant code Small but very well thought set of primitive concepts (Python “time-machine”) Meta-programming: even higher level of abstraction, minor lines of code and/or more general solutions (e.g., ORM) 20
  • 23. ... and libraries But mostly, a simple language encourages developers to write libraries for various tasks Lots of academics and companies wrote libraries for almost every conceivable thing PyPI (31113 libraries alone, plus all the project not indexed but in GitHub, Bitbucket, Google Code or Sourceforge) More on that later... 21
  • 24. Why learning a new language Because it makes easier to perform some tasks To land a (better) job To work with some other software/in some environment To learn a new way of thinking 22
  • 25. Python Community Pycon US, EuroPython Pycon.it, Python Italia A.P.S. Widely used in the open source community: several key projects are written in Python, and it is a default component for several Linux distributions Friendly and supportive community (very good social capital), some “huge” names are Italians (and can help) 23
  • 26. 24
  • 27. Python Jobs Learning new (good) languages is always good, even if you are not going to use them (remember Perlis) Python Paradox (see Graham, ) Several companies use Python And often they are the “right” companies to work with Job demand higher than job offer 25
  • 28. Companies 26 ITA Software Heroku, eBay, Microsoft, Canonical, Spotify, RedHat, Amazon, Netflix, Adroll, Rackspace, Box, Dropbox, Facebook, Guidebook, Oracle, Reddit, ....
  • 29. Why learning a new language Because it makes easier to perform some tasks To land a (better) job To work with some other software/in some environment To learn a new way of thinking 27
  • 30. Scripting 3rd Party 28 SIMULIA Abaqus FEA Blender, Cinema 4D, Lightwave, Houdini, Maya, modo, MotionBuilder, Softimage, Nuke, GIMP, Inkscape, Scribus and Paint Shop Pro, GNU Debugger, ArcGIS, QGIS UNIX
  • 31. Python Concurrency Threads (bad solution, as always) Twisted (asynchronous programming) gevent (“light” threading for massive concurrency) multiprocess (yeah, it’s UNIX!) MPI, CUDA, etc... 29
  • 32. Python and the Web Full-stack frameworks (Django, Web2Py, Pylons, ...) MVC, Component Based Multi-DB ORM – URL Dispatcher – Templating System Light-weight frameworks (Flask) WSGI (simple web-server interface language) 30
  • 33. Django One of the most widely used platform in the world Pintertest, Instagram, Washington Post, ORM, URL Dispatcher, Web Templating System Automatic “Admin” generation from the Model Automatic translation from web forms to entities Built-in internationalization Buil-in caching system Extensible (built-in) authentication system Auto RSS & Atom generation Built-in commenting system Semi-auto Google Sitemap Generation Mitigation system for several security issues (SQL Injection, Cross-site scripting, ...) 31
  • 34. Django Example 32 from django.db import models class Poll(models.Model): question = models.CharField(max_length=200) pub_date = models.DateTimeField('date published') class Choice(models.Model): poll = models.ForeignKey(Poll) choice_text = models.CharField(max_length=200) votes = models.IntegerField(default=0) >>> Poll.objects.all() [<Poll: What's up?>] # Django provides a rich database lookup API that's entirely driven by # keyword arguments. >>> Poll.objects.filter(id=1) [<Poll: What's up?>] >>> Poll.objects.filter(question__startswith='What') [<Poll: What's up?>]
  • 36. Flask Hello, World! 34 from flask import Flask app = Flask(__name__) @app.route("/") def hello(): return "Hello World!" if __name__ == "__main__": app.run() Extremely minimal web framework Minimal memory requirements Also comes with built-in server Compact and easy to write E.g., web interface to a Raspberry PI
  • 37. HIS EX, T E M P O R NUMERIC PYTHON • Numpy (low-level numerical computations) + Scipy (lots of additional packages) • Pandas (R-like) • IPython (wonderfull command line interpreter) + IPython Notebook (“Mathematica-like” interactive documents) • HDF5 (PyTables, H5Py), Databases • Specific libraries for machine learning, etc. • General Purpose Object Oriented Programming
  • 41.
  • 42. DENIQU E G U B E R G R E N Our Code Numpy Atlas/MKL Improvements Improvements Algorithms are fast because of highly optimized C/Fortran code 4 30 LOAD_GLOBAL 1 (dot) 33 LOAD_FAST 0 (a) 36 LOAD_FAST 1 (b) 39 CALL_FUNCTION 2 42 STORE_FAST 2 (c) NUMPY STACK c = a · b
  • 43. ndarray ndarray Memory behavior shape, stride, flags (i0, . . . , in 1) ! I Shape: (d0, …, dn-1) 4x3 An n-dimensional array references some (usually contiguous memory area) An n-dimensional array has property such as its shape or the data-type of the elements containes Is an object, so there is some behavior, e.g., the def. of __add__ and similar stuff N-dimensional arrays are homogeneous
  • 44. (i0, . . . , in 1) ! I C-contiguousF-contiguous Shape: (d0, …, dn) IC = n 1X k=0 ik n 1Y j=k+1 dj IF = n 1X k=0 ik k 1Y j=0 dj Shape: (d0, …, dk ,…, dn-1) Shape: (d0, …, dk ,…, dn-1) IC = i0 · d0 + i14x3 IF = i0 + i1 · d1 ElementLayout inMemory
  • 45. Stride C-contiguous F-contiguous sF (k) = k 1Y j=0 dj IF = nX k=0 ik · sF (k) sC(k) = n 1Y j=k+1 dj IC = n 1X k=0 ik · sC(k) Stride C-contiguousF-contiguous C-contiguous (s0 = d0, s1 = 1) (s0 = 1, s1 = d1) IC = n 1X k=0 ik n 1Y j=k+1 dj IF = n 1X k=0 ik k 1Y j=0 dj
  • 47.
  • 48.
  • 63. Vectorize! Don’t use explicit for loops unless you have to!