Intro to Python – From Programmer to Programmers – pip



Intro to Python – From Programmer to Programmers – pip

0 0


TalkPythonIntro

Slides for my talk Intro to Python

On Github ajlopez / TalkPythonIntro

Intro to Python

From Programmer to Programmers

Created by @ajlopez

https://github.com/ajlopez/TalkPythonIntro

https://github.com/ajlopez/AprendiendoPython

Using reveal.js

Python

  • Dynamic language
  • General purpose
  • Object-oriented, imperative, functional programming
  • Multiplatform
  • CPython, open source
  • Created by Guido van Rossum (late 1980s)
Oh hey, these are some notes. They'll be hidden in your presentation, but you can see them if you open the speaker notes window (hit 's' on your keyboard).

Interactive Interpreter

c:>python
Python 3.2.2 (default, Sep  4 2011, 09:51:08) [MSC v.1500 32 bit (Intel)] on win
32
Type "help", "copyright", "credits" or "license" for more information.
>>>

Running Python

hello.py

print('Hello, world')

Running hello.py

python hello.py

Unix/Linux

Add shebang at the beginning of the file

#!/usr/bin/python

If you don't know where is python

#!/usr/bin/env python

Make hello.py executable

chmod a+x hello.py

Numbers

Integers and Reals

>>> 2 + 2
4
>>> 53672 + 235253
288925
>>> 1 / 2 # python 3.x
0.5
>>> 9 % 3
0
>>> 2.75 % 0.5
0.25

Large numbers

>>> 1000000000000000000
1000000000000000000L
>>> 1987163987163981639186L * 198763981726391826L + 23
394976626432005567613000143784791693659L

Built-in functions

>>> pow(2, 3)
8
>>> abs(-10)
10
>>> pow
<built-in functin pow>
>>> abs
<built-in functin abs>

Conversion

>>> int(3/2)
1
>>> float(5)
5.0
>>> int
<class 'int'>
>>> float
<class 'float'>

Module math

Import math

>>> import math
>>> math.sqrt(2)
1.4142135623730951
>>> math.floor(32.9)
32
>>> math
<module 'math' (built-in)>
>>> dir(math)
['__doc__', '__name__', '__package__', 'acos', 'acosh', 'asin', 'asinh', 
 'atan', 'atan2', 'atanh', 'ceil', 'copysign', 'cos', 'cosh', 'degrees', 
 'e', 'erf', 'erfc', 'exp', 'expm1', 'fabs', 'factorial', 'floor', 
 'fmod', 'frexp', 'fsum', 'gamma', 'hypot', 'isfinite', 'isinf', 'isnan', 
 'ldexp', 'lgamma', 'log', 'log10', 'log1p', 'modf', 'pi', 'pow', 
 'radians', 'sin', 'sinh', 'sqrt', 'tan', 'tanh', 'trunc']

Partial import

>>> from math import sqrt
>>> sqrt(9)
3.0

But...

>>> math.sqrt(-1)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: math domain error

Complex numbers

>>> import cmath
>>> cmath.sqrt(-1)
1j
>>> (1+3j) * (9+4j)
(-3+31j)

Strings

String constants

>>> "Hello, world"
'Hello, world'
>>> 'Hello, world'
'Hello, world'

Concatenating Strings

>>> 'Hello, ' 'world'
'Hello, world'
>>> "\"Hello, world!\" she said"
'"Hello, world!" she said'
>>> "Hello, " + "world!"
'Hello, world!'
>>> x = "Hello, "
>>> y = "world!"
>>> x + y
'Hello, world!'

Long Strings

print '''This is a very long string.
It continues here.
And it's not over yet.
"Hello, world!"
Still here.'''

Variables

Scope

>>> def foo(): x = 42
...
>>> x = 1
>>> foo()
>>> x
1

All is a Dictionary

>>> x = 1
>>> scope = vars()
>>> scope['x']
1
>>> scope['x'] += 1
>>> x
2

List, Tuples, Dictionaries

Accesing Values

>>> a = [1,2,3]
>>> a[1]
2
>>> a[1:2]
[2]
>>> a[-1]
3
>>> a[-1:]
[3]
>>> a[:-1]
[1, 2]

Example Method: Index

>>> knights = ['We', 'are', 'the', 'knights', 'who', 'say', 'ni']
>>> knights.index('who')
4
>>> knights.index('herring')
Traceback (innermost last):
File "<pyshell#76>", line 1, in ?
knights.index('herring')
ValueError: list.index(x): x not in list

More: dir(knights)

Dictionaries

Create a dictionary

d = {'x': 1, 'y': 2, 'z': 3}
e = dict(x=1, y=2, z=3)

Iterate

for key in d:
  print key, 'corresponds to', d[key]

Iterate keys, values

for key, value in d.items():
  print key, 'corresponds to', value

Simple Statements

Conditionals

None and False are false.

number = input('Enter a number between 1 and 10: ')
if number <= 10 and number >= 1:
  print 'Great!'
else:
  print 'Wrong!'

Loops

for

words = ['this', 'is', 'an', 'ex', 'parrot']
for word in words:
  print word

while

while True:
  word = input('Please enter a word: ')
  if not word: break
  # do something with the word:
  print 'The word was ' + word

They have break and continue

Functions

Simple

def foo():
  print("Hello, world")

Nested

def multiplier(factor):
  def multiplyByFactor(number):
    return number*factor
  return multiplyByFactor

Parameters

def print_params(x, y, z=3, *pospar, **keypar):
  print x, y, z
  print pospar
  print keypar

Classes and Objects

First Example

class Foo:
   def say(self, msg):
      print(msg)

f = Foo()
f.say('hello')

Empty Class

class Empty:
  pass

Constructors and Privacy

__init__ is invoked at beginning

Names with initial __ are private

class Dog:
  def __init__(self, name):
    self.__name = name

  def getName(self):
    return self.__name

Inheritance

class Animal:
  def __init__(self):
    print("Animal created")

class Dog(Animal):
  def __init__(self, name):
    super(Animal, self).__init__()
    self.__name = name

Modules

Modules are Programs

hello.py

def say(name):
    print("Hello,", name)

In other program or interpreter

import hello
hello.say('Adam')
from hello import say
say('Adam')

Running Modules

hello.py

def say(name):
    print("Hello,", name)

def test():
    say('World')

if __name__ == '__main__':
    test()

Searching Modules

import sys
import pprint

pprint.pprint(sys.path)

In my machine

['',
 'd:\\Python332\\lib\\site-packages\\distribute-0.6.45-py3.3.egg',
 'C:\\Windows\\SYSTEM32\\python33.zip',
 'd:\\Python332\\DLLs',
 'd:\\Python332\\lib',
 'd:\\Python332',
 'd:\\Python332\\lib\\site-packages',
 'd:\\Python332\\lib\\site-packages\\win32',
 'd:\\Python332\\lib\\site-packages\\win32\\lib',
 'd:\\Python332\\lib\\site-packages\\Pythonwin',
 'd:\\Python332\\lib\\site-packages\\setuptools-0.6c11-py3.3.egg-info']

Packages

They are directories

>>> import sqlite3
>>> sqlite3.__file__
'd:\\Python332\\lib\\sqlite3\\__init__.py'
>>> import distutils
>>> distutils.__file__
'd:\\Python332\\lib\\distutils\\__init__.py'

Metaprogramming

Creating a Class

Globals, Locals, Exec

List globals

globals()

List locals

globals()

Execute code

exec('one = 1')

See

print(exec.__doc__)

pip

A tool for installing and managing Python packages.

Installing pip

See installing pip

In my Windows 8 machine:

Web Development

Flask

http://flask.pocoo.org/

Django

https://www.djangoproject.com/

  • Install with pip install Django
  • Run django-admin.py startproject my site
  • Windows: python <pypath>\Scripts\django-admin.py startproject mysite
  • cd mysite
  • python manage.py runserver 8080

For database setup edit mysite/settings.py

Polls Application

Create the application with

python manage.py startapp polls

A new folder is created:

polls/
    __init__.py
    models.py
    tests.py
    views.py

Resources

THE END

BY Angel 'Java' Lopez / www.ajlopez.com / @ajlopez