"Python is an interpreted high-level programming language
for general-purpose programming. It has a design
philosophy that emphasizes code readability, and a syntax
that allows programmers to express concepts in fewer lines of code,
notably using significant whitespace.
Python features a dynamic type system and
automatic memory management. It supports multiple programming
paradigms, including object-oriented, imperative, functional and
procedural, and has a large and comprehensive standard library."
— Wikipedia
Code blocks defined with indentation
# for comments
>>> a = 10
>>> a
10
>>> a = 10
>>> a
10
>>> a = 0.10
>>> a
0.10
>>> a = "Hola"
>>> a
'Hola'
Delimiters can be: " or '
>>> a = True
>>> a
True
Only True or False
>>> a = ('1', 23, -12.3232)
>>> a
('1', 23, -12.3232)
>>> a[0]
'1'
>>> a[1]
23
>>> a[2]
-12.3232
>>> a[-1]
-12.3232
Immutable
>>> a = ['1', 23, -12.3232]
>>> a
['1', 23, -12.3232]
>>> a.append("extra")
>>> a
['1', 23, -12.3232, 'extra']
Mutable
a = {"first": '1', "second": 23, "third":-12.3232}
>>> a
{'second': 23, 'first': '1', 'third': -12.3232}
>>> a["third"]
-12.3232
>>> a["fourth"] = 2
>>> a
{'second': 23, 'first': '1', 'third': -12.3232, 'fourth': 2}
Mutable
Named keys
Keys not in order
>>> a = []
>>> b = a
>>> b.append(1)
>>> a
[1]
>>> b
[1]
Be careful with mutable types!
if condition1:
# body for condition1
# This is only processed if condition1 is evaluated to True
elif condition2:
# body for condition2
...
elif conditionN:
# body for conditionN
else:
# body for others
Condition must evaluate to `True` or `False`.
while a < 10:
# will be repeated until `a` is greater or equal than 10
for i in [1,2,3,4]:
# will be repeated four times changing `i`'s value with the
# contents of the array
else:
# This block is executed after the iterations when the iteration
# block didn't end with a `break`.
# Else is optional.
# For this example it's always executed.
operator | meaning |
---|---|
< | strictly less than |
<= | less than or equal |
> | strictly greater than |
>= | greater than or equal |
== | equal |
!= | not equal |
is | object identity |
is not | negated object identity |
in | containment test |
not in | negated containment test |
operator | meaning |
---|---|
+ | addition |
- | subtraction or negative |
* | multiplication |
/ | division |
** | power |
% | remainder |
def fib(num):
"""
This is a documentation block called `docstring`. It's optional.
Read it with `help(fib)`.
"""
res = []
a, b = 0, 1
while a < num:
res.append(a)
a, b = b, a+b
return res # exit with `res` value
>>> fib(10)
[0, 1, 1, 2, 3, 5, 8]
>>> result = fib(40)
>>> result
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
>>> def test1():
... a = 1 # Local variable declaration, only accessible here
...
>>> def test2():
... return a # Not declared, a is out of scope
...
>>> test2()
Traceback (most recent call last):
File "stdin", line 1, in module
File "stdin", line 2, in test2
NameError: global name 'a' is not defined
>>> a = 10
>>> def test2():
... return a # `a` is declared in the upper level, it has access
...
>>> test2()
10
def func_creator():
a = 10 # local variable
def incrementer( arg ):
return arg + a # `a` is in scope
return incrementer
>>> inc = func_creator()
>>> inc
function incrementer at 0x7f52f8947668
>>> inc(10) # incrementer function remembers `a`
20
>>> a # Not in scope!
Traceback (most recent call last):
File "stdin", line 1, in module
NameError: name 'a' is not defined
>>> inc = lambda x: x+1
>>> inc(1)
2
>>> inc(10)
11
>>> inc
function lambda at 0x7f52f8947758
>>> f = open('Quixote.txt', 'r') # `r` is the mode
>>> f.read()
'En un lugar de La Mancha, de cuyo nombre no quiero acordarme...
>>> f.close()
Open and Close make System Calls internally
>>> with open('Quixote.txt', 'r') as f:
... f.read()
When the block ends the file is closed automatically
A Module is a file.
A Package is a directory of Modules.
Use __init__.py mark directories as Packages.
>>> import math # imports math and leaves it in `math` namespace
>>> math.pow(2, 4) # `math` prefix is needed
16.0
>>> from math import pow # from `math` only import pow to the local scope
>>> pow(2, 4) # no prefix needed
16.0
>>> from math import pow as p # like before but with a different name
>>> p(2,4)
16.0
Defined by sys.path variable.
python modulename.py [args]
Runs with __name__ == '__main__'
if __name__ == "__main__":
import sys # This block won't run if the module is imported
fib(int(sys.argv[1])) # but it will when it's executed directly
class Dog:
kind = 'canine' # class variable shared by all instances
def __init__(self, name):
self.name = name # instance variable unique to each instance
>>> d = Dog('Fido') # create a new instance named Fido
>>> e = Dog('Buddy') # create a new instance named Buddy
>>> d.kind # shared by all dogs
'canine'
>>> e.kind # shared by all dogs
'canine'
>>> d.name # unique to d
'Fido'
>>> e.name # unique to e
'Buddy'
Classes can be inherited, and then extended:
class Dog(Animal):
# Will have the same methods than Animal
# Can override or extend methods.
Python has many standard interfaces.
If a custom class fulfills any of them it can be used as standard.
class Counter:
def __init__(self, low, high):
self.current = low
self.high = high
def __iter__(self):
return self
def __next__(self):
if self.current > self.high:
raise StopIteration
else:
self.current += 1
return self.current - 1
>>> for c in Counter(3, 8): # Prints 3,4,5,6,7,8
>>> print c