respecting python tutorial and stock python-tips
for standard objects and modules, see Python Standard Library
for language reference, see Python Language Reference
- annotation
- break
- condition
- del
- dict
- docstring
- for
- function
- if
- interpreter
- lambda
- lists
- modules
- numbers
- pass
- sets
- string
- tuple
- range
on top of the file, add
#!/usr/bin/env python3.1
on top of the file, add
# -*- coding: encoding -*-
>>> knights = {'gallahad': 'the pure', 'robin': 'the brave'}
>>> for k, v in knights.items():
... print(k, v)
...
gallahad the pure
robin the brave
>>> for i, v in enumerate(['tic', 'tac', 'toe']):
... print(i, v)
...
0 tic
1 tac
2 toe
>>> questions = ['name', 'quest', 'favorite color']
>>> answers = ['lancelot', 'the holy grail', 'blue']
>>> for q, a in zip(questions, answers):
... print('What is your {0}? It is {1}.'.format(q, a))
...
What is your name? It is lancelot.
What is your quest? It is the holy grail.
What is your favorite color? It is blue.
To loop over a sequence in reverse, first specify the sequence in a forward direction and then call the reversed() function
>>> for i in reversed(range(1, 10, 2)):
... print(i)
...
9
7
5
3
1
>>> basket = ['apple', 'orange', 'apple', 'pear', 'orange', 'banana']
>>> for f in sorted(set(basket)):
... print(f)
...
apple
banana
orange
pear
to change a list while you are looping over it; however, it is often simpler and safer to create a new list instead
>>> import math
>>> raw_data = [56.2, float('NaN'), 51.7, 55.3, 52.5, float('NaN'), 47.8]
>>> filtered_data = []
>>> for value in raw_data:
... if not math.isnan(value):
... filtered_data.append(value)
...
>>> filtered_data
[56.2, 51.7, 55.3, 52.5, 47.8]