Python Basics: Difference between revisions
Jump to navigation
Jump to search
(6 intermediate revisions by the same user not shown) | |||
Line 18: | Line 18: | ||
if __name__ == "__main__": | if __name__ == "__main__": | ||
test() | test() | ||
</source> | </source> | ||
== Object Types == | == Object Types == | ||
* | * Null: None | ||
* | * Boolean: True, False (Python >= 2.3) | ||
* | * Numeric: int, long, float, complex | ||
* | * Sequence: str, tuple, list (lists are mutable, tuples aren't) | ||
* Mapping: dict | |||
* | |||
* Others: type, function, classobj, instance | * Others: type, function, classobj, instance | ||
* Lists and dictionaries are mutable. | |||
<source lang="python"> | <source lang="python"> | ||
type(object) # returns the type of object | type(object) # returns the type of object | ||
Line 43: | Line 34: | ||
== Implied Boolean == | == Implied Boolean == | ||
None, numeric 0, empty | None, numeric 0, empty sequence or dict are all false. Otherwise true. | ||
== Literals == | == Literals == | ||
Line 56: | Line 47: | ||
[ 42, 3.14, 'hello' ] # List | [ 42, 3.14, 'hello' ] # List | ||
( 100, 200, 300 ) # Tuple (parentheses optional) | ( 100, 200, 300 ) # Tuple (parentheses optional) | ||
{ 'x':42, 'y':3.14 } # Dictionary | { 'x':42, 'y':3.14 } # Dictionary | ||
</source> | </source> | ||
Line 96: | Line 86: | ||
== Operations on Strings == | == Operations on Strings == | ||
< | <syntaxhighlight lang="python"> | ||
# formatted positional variable interpolation | # formatted positional variable interpolation | ||
'My name is %s, my age is %d' % (name, age) | 'My name is %s, my age is %d' % (name, age) | ||
Line 141: | Line 131: | ||
S.translate(table [, delchars]) | S.translate(table [, delchars]) | ||
S.upper( ) # 'Abcdef' | S.upper( ) # 'Abcdef' | ||
</ | </syntaxhighlight> | ||
== List-Specific Operations == | == List-Specific Operations == |
Latest revision as of 16:40, 4 May 2017
Program Structure
- # for comments
- continue a line with \, or wrap in () or [] or {}
- block structure:
block header: one-liner
or
block header:
block line 1
block line 2
etc
- use "
pass
" when your block header needs no statements - use this to have your python file run the test() function by default when executed:
if __name__ == "__main__":
test()
Object Types
- Null: None
- Boolean: True, False (Python >= 2.3)
- Numeric: int, long, float, complex
- Sequence: str, tuple, list (lists are mutable, tuples aren't)
- Mapping: dict
- Others: type, function, classobj, instance
- Lists and dictionaries are mutable.
type(object) # returns the type of object
isinstance(1, int) # returns true
Implied Boolean
None, numeric 0, empty sequence or dict are all false. Otherwise true.
Literals
42 # Integer literal
3.14 # Floating-point literal
1.0J # Imaginary literal
'hello' # String literal
"world" # Another string literal
"""Good
night""" # Triple-quoted string literal
[ 42, 3.14, 'hello' ] # List
( 100, 200, 300 ) # Tuple (parentheses optional)
{ 'x':42, 'y':3.14 } # Dictionary
Variables
The underscore is the only legal punctuation in a variable name. Variables can only be created by binding them to an object. An object is garbage collected when there are no more references to it.
a = b = c = 1 # multiple assignment
x, y = 1, 2 # unpacking assignment with tuples
del x
Expressions
5 < x < 10 # chaining
x is y, x is not y # identity test (same object)
x == y, x != y # equivalence test (same values)
x in y, x not in y # membership
x and y # returns y if x is true, otherwise returns x
x or y # returns x if x is true, otherwise returns y
<source>
== Operations on Sequences ==
<source lang="python">
tuple("abc") # ('a', 'b', 'c')
list("abc") # ['a', 'b', 'c']
"abcdef"[2] # 'c' (indexing)
"abcdef"[-1] # 'f'
"abcdef"[2:4] # 'cd' (slicing)
"abcdef"[2:] # 'cdef'
"abcdef"[:4] # 'abcd'
"abcdef"[:] # 'abcdef' (slicing to copy)
len("abcdef") # 6 (length)
'abc' + 'def' # 'abcdef' (concatenation)
'-'*80 # (a string of 80 hyphens)
'abcdef'.count('c') # 1
'abcdef'.index('c') # 2
Operations on Strings
# formatted positional variable interpolation
'My name is %s, my age is %d' % (name, age)
# formatted dictionary-based variable interpolation
'My name is %(name)s, my age is %(age)d' % {'name': name, 'age', age}
# number formats
"file_%03d.txt" % 2 # "file_002.txt"
"5-day increase: %3.1f%%" % 2.6453 # "5-day increase: 2.6%"
S = "abcdef"
S[2:4] # 'cd' substring
S.capitalize( ) # 'Abcdef'
S.center(10, '-') # '--abcdef--'
S.count('cd') # 1
S.encode([encoding [,errors]]) # ???
S.endswith('cd') # False
S.expandtabs([tabsize])
S.find('cde') # 2
S.index('cde') # 2
S.isalnum( ) # True
S.isalpha( ) # True
S.isdigit( ) # False
S.islower( ) # True
S.isspace( ) # False
S.istitle( ) # False
S.isupper( ) # False
S.join('---') # '-abcdef-abcdef-'
S.ljust(10) # 'abcdef '
S.lower( ) # 'abcdef'
S.lstrip( ) # 'abcdef'
S.replace('a', '1') # '1bcdef'
S.rfind('cde') # 2
S.rindex('cde') # 2
S.rjust(10) # ' abcdef'
S.rstrip( ) # 'abcdef'
S.split('c') # ['ab', 'def']
'Hi\nthere, mister'.split() # ['Hi', 'there,', 'mister']
S.splitlines() # ['abcdef']
'Hi\nthere, mister'.splitlines() # ['Hi', 'there, mister']
S.startswith('cd') # False
S.strip( ) # 'abcdef'
S.strip('af') # 'bcde'
S.swapcase( ) # 'ABCDEF'
S.title( ) # 'Abcdef'
S.translate(table [, delchars])
S.upper( ) # 'Abcdef'
List-Specific Operations
x = [1, 2] # in the following examples, x is reset each time
x.append(3) # x == [1, 2, 3]
x.extend([3, 4]) # x == [1, 2, 3, 4]
x.insert(1, 1.5) # x == [1, 1.5, 2]
x.remove(1) # x == [2]
y = x.pop() # x == [1] and y == 2
x.reverse() # x == [2, 1]
x.sort() # x == [1, 2] (may provide a comparison function)
x = ['a', 'b', 'c']
"\t".join(x) # x == "a b c"
Custom Sort Example
def numeric_compare(a, b):
return a-b
x.sort(numeric_compare)
Dictionaries
x = {'a':1, 'b':2} # in the following examples, x is reset each time
x['c'] = 3 # add a (key, value) pair
'a' in x # True (in matches keys)
x.copy() # {'a': 1, 'b': 2} (shallow copy)
x.items() # [('a', 1), ('b', 2)] (shallow copy)
x.keys() # ['a', 'b'] (shallow copy)
x.values() # [1, 2] (shallow copy)
x['a'] # 1
x.get('a') # 1
x.get('c') # None (x['c'] gives an error)
x.get('c', 0) # 0 (supplied default value)
x.setdefault('a', 3) # 1 (since 'a' is a valid key)
x.setdefault('c', 3) # 3, x == {'a':1, 'b':2, 'c':3}
x.clear() # x == {}
x.update({'a':3,'c':3}) # x == {'a': 3, 'c': 3, 'b': 2}
x.pop('a') # x == {'b': 2}
x.popitem() # ('a', 1), x == {'b':2} (item randomly selected)
TODO: iteritems, iterkeys, itervalues
Control Flow
NOTE: There is no switch/case statement in Python.
if x < 0: print "x is negative"
elif x % 2: print "x is positive and odd"
else: print "x is even and non-negative"
while <test>: # Loop test
<statements1> # Loop body
else: # Optional else
<statements2> # Run if didn't exit loop with break
x = y / 2 # For some y > 1
while x > 1:
if y % x == 0: # Remainder
print y, 'has factor', x
break # Skip else
x = x-1
else: # Normal exit
print y, 'is prime'
for letter in "ciao":
print "give me a", letter, "..."
for x in range(5,25,5): # use xrange() for better performance
print x, # 5 10 15 20
for key in dictionary:
print key, "->", dictionary[key]
for key, value in dictionary.items( ):
if not key or not value: del d[key] # keep only true keys and values
for key in tests:
if key in items:
print key, "was found"
else:
print key, "not found!"
break
exits the current loopcontinue
jumps to the top of the loop
List Comprehensions
[ord(x) for x in 'spam'] # [115, 112, 97, 109]
[x for x in range(5) if x % 2 == 0] # [0, 2, 4]
[(x,y) for x in range(5) if x%2 == 0 for y in range(5) if y%2 == 1]
# [(0, 1), (0, 3), (2, 1), (2, 3), (4, 1), (4, 3)]
Functions
def double(x): return x*2
f = double # functions are objects too.
f(4) # 8 (parentheses trigger evaluation)
def add(x, y=0): return x+y # default argument
print add(5, 6) # 11
print add(5) # 5
def orderPrint(left, right): print left, right
orderPrint("L", "R") # L R
orderPrint(right="R", left="L") # L R (named arguments)
f = lambda x, y, z: x + y + z # anonymous function
f(2, 3, 4) # 9
# a function that uses "yield" is called a generator
# requires Python >= 2.3
def updown(N):
for x in xrange(1,N): yield x
for x in xrange(N,0,-1): yield x
for i in updown(3): print i # 1 2 3 2 1
Classes
class Test:
def __init__(self, value = 1): self.x = value
def increment(self): self.x += 1
def __str__(self): return str(self.x)
for x in Test(), Test(5):
print x,; x.increment(); print x, # 1 2 5 6
class TestList(list):
def __init__(self, min, max):
for i in range(min, max):
self.append(i)
TestList(3, 9) # [3, 4, 5, 6, 7, 8]
class Counter(dict):
def count(self, key):
if key in self: self[key] += 1
else: self[key] = 1
Other special class methods:
__repr__ # for `x`
__eq__ # for x == a
__cmp__ # for x < a, x > a, etc.
__hash__ # for x as dictionary key
__len__ # for len(x)
__nonzero__ # for x as Boolean
__call__ # for x(args)
__getitem__ # for x[i]
__contains__ # for "a in x"
__iter__ # for "for a in x"
Exceptions
try:
currentDate = dateIterator.next()
except StopIteration:
print "no more dates!"
Blanket exception is Exception
.