Built-in
Funzioni
Indice Funzioni |
|||||||||
Errori
Funzioni
_
1
__debug__
1
__doc__
1
__import__
1
__name__
1
abs
1 >>> abs(-2) # Ritorna il valore assoluto del numero
2 2
3 >>> abs(5)
4 5
5 >>> abs(0)
6 0
all
1 >>> all([1, 2, 3]) # Ritorna True se tutti gli elementi dell'Iterable sono True
2 True
3 >>> all([0, 1, 2]) # altrimenti False
4 False
5 >>> all(['foo', 'bar', 'baz'])
6 True
7 >>> all(['foo', 'bar', ''])
8 False
any
1 >>> any([1, 2, 3]) # Ritorna True se c'è almeno un elemento True nell'Iterable
2 True
3 >>> any([0, '', None]) # altrimenti False
4 False
5 >>> any([0, '', None, 8])
6 True
7 >>> any(['foo', 'bar', ''])
8 True
apply
1 >>> def func(x, y, z): return x*y - z
2 ...
3
4 >>> apply(func, (3,4,2)) # Passando una sequenza come secondo argomento si
5 10 # associano gli argomenti in base alla posizione
6 >>> func(3,4,2) # ed equivale a questa chiamata
7 10
8
9 >>> apply(func, (), {'z':2, 'x':3, 'y':4}) # Passando un dizionario come terzo argomento si
10 10 # associano gli argomenti in base al nome
11 >>> func(z=2, x=3, y=4) # ed equivale a questa chiamata
12 10
basestring
1
bool
1 >>> bool(5) # Ritorna True se l'argomento è True, altrimenti False
2 True
3 >>> bool('foo')
4 True
5 >>> bool(-2)
6 True
7 >>> bool([0])
8 True
9 >>> bool([0, None]) # La lista contiene elementi quindi è True
10 True
11 >>> bool([])
12 False
13 >>> bool('')
14 False
15 >>> bool(0)
16 False
17 >>> bool(5 > 50)
18 False
19 >>> bool(5 > 3)
20 True
21 >>> bool(5 == 5.0)
22 True
23 >>> bool(5 in [1,3,5,7,9])
24 True
25 >>> bool(2 in [1,3,5,7,9])
26 False
27 >>> bool('key1' in {'key1': 'value1', 'key2': 'value2'})
28 True
29 >>> bool('value1' in {'key1': 'value1', 'key2': 'value2'})
30 False
buffer
1
callable
1
chr
1 >>> chr(97) # Ritorna il carattere corrispondente al valore ascii.
2 'a'
3 >>> for x in range(97,123):
4 ... print chr(x),
5 ...
6 a b c d e f g h i j k l m n o p q r s t u v w x y z
classmethod
1
cmp
1 >>> cmp(1,2) # Ritorna -1 se il risultato del confronto tra 'x' e 'y' risulta negativo
2 -1
3 >>> cmp(2,1) # 1 in caso contrario
4 1
5 >>> cmp(1,1) # 0 in caso di uguaglianza
6 0
7 >>> cmp('foo', 'bar')
8 1
9 >>> cmp('foo', 'Foo') # Ritorna True perchè l'ascii di 'f' è 102, mentre quello di 'F' è di 70
10 1
11 >>> cmp('foo', 'foo')
12 0
13 >>> cmp('foo', 'foobar')
14 -1
15 >>> cmp([1,2,3], [1,2,3]) # Nelle liste e nei dizionari fa il confronto fra gli elementi interni
16 0
17 >>> cmp([1,2,3], [1,2,4])
18 -1
19 >>> cmp([1,2,4], [1,2,3])
20 1
21 >>> cmp({'k1': 'v1', 'k2': 'v2'}, {'k1': 'v1', 'k2': 'v2'})
22 0
23 >>> cmp({'k': 'v', 'k2': 'v2'}, {'k1': 'v1', 'k2': 'v2'})
24 -1
25 >>> cmp({'k1': 'v1', 'k2': 'v2'}, {'k1': 'v1', 'k': 'v'})
26 1
27 >>> cmp({'k1': 'v1', 'k2':'v2'}, [1,2,3]) # Tra dizionari e liste il confronto avviene per ordine alfabetico
28 -1
29 >>> cmp({'k1': 'v1', 'k2':'v2'}, 4) # Mentre per i numeri c'è un'eccezione alla regola.
30 1
coerce
1
compile
1
complex
1
copyright
1
credits
1
delattr
1
dict
1 >>> d = dict() # crea un dizionario vuoto
2 >>> d['key'] = 'value'
3 >>> d
4 {'key': 'value'}
5 >>> d = dict([('key','value'), ('key2','value2')]) # Crea un dizionario da una lista di tuple
6 >>> d
7 {'key2': 'value2', 'key': 'value'}
8 >>> d = dict([(x, x**2) for x in range(5)]) # Attraverso una list comprehension che crea tuple
9 >>> d
10 {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}
11 >>> d = dict((x, x+2) for x in range(5)) # Tramite i generatori di espressioni
12 >>> d
13 {0: 2, 1: 3, 2: 4, 3: 5, 4: 6}
14 >>> d = dict(key='value', key2='value2') # crea un dizionario tramite l'operatore di assegnamento '='
15 >>> d
16 {'key2': 'value2', 'key': 'value'}
17 >>> d = dict(key=1234, key2=1234)
18 >>> d
19 {'key2': 1234, 'key': 1234}
dir
1 >>> dir() # Senza argomento restituisce i nomi dello scope corrente
2 ['__builtins__', '__doc__', '__name__']
3
4 >>> dir('') # Se l'argomento è un oggetto, restituisce la lista dei suoi metodi/attributi
5 ['__add__', '__class__', '__contains__', '__delattr__', '__doc__', '__eq__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__getslice__', '__gt__', '__hash__', '__init__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__str__', 'capitalize', 'center', 'count', 'decode', 'encode', 'endswith', 'expandtabs', 'find', 'index', 'isalnum', 'isalpha', 'isdigit', 'islower', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'replace', 'rfind', 'rindex', 'rjust', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']
6
7 >>> import re
8 >>> dir(re) # Se l'argomento è un modulo, restituisce la lista delle sue funzioni/classi/variabili
9 ['DOTALL', 'I', 'IGNORECASE', 'L', 'LOCALE', 'M', 'MULTILINE', 'S', 'U', 'UNICODE', 'VERBOSE', 'X', '__all__', '__builtins__', '__doc__', '__file__', '__name__', 'compile', 'engine', 'error', 'escape', 'findall', 'finditer', 'match', 'purge', 'search', 'split', 'sub', 'subn', 'template']
divmod
1
enumerate
1 >>> mylist = ['foo', 'bar', 'baz']
2 >>> for index, element in enumerate(mylist):
3 ... print "%s all`indice %d" %(element, index)
4 ...
5 foo all`indice 0
6 bar all`indice 1
7 baz all`indice 2
eval
1
execfile
1
exit
1 >>> exit('bye') # Lascia un messaggio all'uscita. Vedi anche ```quit()```
2 bye
3 user@user-desk:~$
4 >>> exit() # Esce senza messaggio
5 user@user-desk:~$
file
1
filter
1
float
1
frozenset
1
getattr
1 def find_by(seq, **kwargs):
2 for obj in seq:
3 for key, val in kwargs.iteritems():
4 try:
5 # solleva un AttributeError se `obj` non ha l'attributo/metodo `key`
6 if getattr(obj, key) != val:
7 break
8 except AttributeError:
9 break
10 else:
11 return obj
12 raise NotFound
13
14
15 class Book(object):
16 def __init__(self, t, a):
17 self.title = t
18 self.author = a
19
20
21 if __name__ == "__main__":
22 books = [Book('Python in a Nutshell', 'Alex Martelli'),
23 Book('Python Pocket', 'Marco Beri'),
24 Book('Learning Python','Lutz - Ascher')]
25 alex_book = find_by(books, author='Alex Martelli')
26 learning_python = find_by(books, title='Learning Python')
27 mark_book = find_by(books, author='Marco Beri')
28 print "%s ha scritto il libro %s" % (alex_book.author, alex_book.title)
29 print "%s ha scritto il libro %s" % (mark_book.author, mark_book.title)
30 print "%s e` stato scritto da %s" \
% (learning_python.title, learning_python.author)
globals
1
hasattr
1 >>> class Foo:
2 ... foo = 'bar'
3 ... bar = 'foo'
4 ...
5 >>> hasattr(Foo, 'foo') # Ritorna True se l'attributo è presente nella classe
6 True
7 >>> hasattr(Foo, 'bar')
8 True
9 >>> hasattr(Foo, 'foobar') # altrimenti False
10 False
hash
1
help
1
hex
1
id
1 >>> x = 'foo' # Ritorna l'id di un oggetto. Corrisponde all'indirizzo di memoria dell'oggetto stesso.
2 >>> id(x)
3 11019872
4 >>> id('foo')
5 11019872
6 >>> y = x
7 >>> id(y)
8 11019872
9 >>> x = 'bar'
10 >>> id(x)
11 10332160
input
1
int
1
intern
1
isinstance
1
issubclass
1
iter
1
len
1 >>> len('python') # Ritorna la lunghezza dell'oggetto dato
2 6
3 >>> len(['foo' ,'bar', 'baz'])
4 3
5 >>> len({1:'foo', 2:'bar', 3:'baz'}) # Ci sono 3 coppie chiave/valore
6 3
7 >>> len('')
8 0
license
1 >>> license() # Mostra la licenza di Python
2 A. HISTORY OF THE SOFTWARE
3 ==========================
4
5 Python was created in the early 1990s by Guido van Rossum at Stichting
6 Mathematisch Centrum (CWI, see http://www.cwi.nl) in the Netherlands
7 as a successor of a language called ABC. Guido remains Python's
8 principal author, although it includes many contributions from others.
9
10 ............... # Continua...
list
1
locals
1
long
1
map
1
max
1
min
1
object
1
oct
1
open
1
ord
1 >>> ord('a') # Ritorna il valore ascii del carattere.
2 97
3 >>> for x in 'fooBar': print ord(x),
4 ...
5 102 111 111 66 97 114
pow
1
property
1
quit
1 >>> quit() # Esce dall'interprete/programma
2 user@user-desk:~$
3 >>> quit('byebye') # Esce lanciando un messaggio
4 byebye
5 user@user-desk:~$
range
1
raw_input
1
reduce
1
reload
1
repr
1
reversed
1
round
1 >>> round(1) # Di default arrotonda di una sola cifra
2 1.0
3 >>> round(1.2343, 2)
4 1.23
5 >>> round(10.34633, 3)
6 10.346
7
8 NOTA: Invece di usare 'n = %f' % round(1.234567, 2) e` consigliato usare 'n= %.2f' % 1.234567, dove le cifre dopo la virgola sono specificate con %.Nf
set
1
setattr
1
slice
1
sorted
1
staticmethod
1
str
1
sum
1 >>> sum([1,2,3,4,5]) # Senza il secondo parametro ritorna la somma di una sequenza
2 15
3 >>> sum([1,2,3,4,5], 5) # Ritorna la somma della sequenza + il valore del secondo parametro dato.
4 20
5 >>> sum([],5) # Ritorna solo il secondo parametro
6 5
super
1
tuple
1
type
1 >>> type('foo') # Ritorna il tipo del valore passato
2 <type 'str'>
3 >>> type(5)
4 <type 'int'>
5 >>> type(5.0)
6 <type 'float'>
7
8 >>> class foo: pass
9 ...
10 >>> type(foo)
11 <type 'classobj'>
12 >>> bar = foo()
13 >>> type(bar)
14 <type 'instance'>
15
16 >>> def foobar(): pass
17 ...
18 >>> type(foobar)
19 <type 'function'>
20
21 >>> import re
22 >>> type(re)
23 <type 'module'>
unichr
1
unicode
1
vars
1 >>> lib = 'libreria'
2 >>> nLibri = 250
3 >>> print "La %(lib)s ha piu` di %(nLibri)s libri" % vars()
4 La libreria ha piu` di 250 libri
xrange
1
zip
1
Errori
ArithmeticError
1
AssertionError
1
AttributeError
1
BaseException
1
DeprecationWarning
1
EOFError
1
Ellipsis
1
EnvironmentError
1
Exception
1
False
1
FloatingPointError
1
FutureWarning
1
GeneratorExit
1
IOError
1
ImportError
1
ImportWarning
1
IndentationError
1
IndexError
1
KeyError
1
KeyboardInterrupt
1
LookupError
1
MemoryError
1
NameError
1
None
1
NotImplemented
1
NotImplementedError
1
OSError
1
OverflowError
1
PendingDeprecationWarning
1
ReferenceError
1
RuntimeError
1
RuntimeWarning
1
StandardError
1
StopIteration
1
SyntaxError
1
SyntaxWarning
1
SystemError
1
SystemExit
1
TabError
1
True
1
TypeError
1
UnboundLocalError
1
UnicodeDecodeError
1
UnicodeEncodeError
1
UnicodeError
1
UnicodeTranslateError
1
UnicodeWarning
1
UserWarning
1
ValueError
1
Warning
1
ZeroDivisionError
1
Collegamenti Esterni