Python3 Basics: Difference between revisions
Jump to navigation
Jump to search
(7 intermediate revisions by the same user not shown) | |||
Line 39: | Line 39: | ||
* <code>set</code> | * <code>set</code> | ||
* <code>dict</code> | * <code>dict</code> | ||
* Others: type, function, classobj, instance | * Others: dictionary views, iterators, type, function, classobj, instance | ||
<source lang="python"> | <source lang="python"> | ||
type(object) # returns the type of object | type(object) # returns the type of object | ||
Line 79: | Line 79: | ||
x and y # returns y if x is true, otherwise returns x | x and y # returns y if x is true, otherwise returns x | ||
x or y # returns x if x is true, otherwise returns y | x or y # returns x if x is true, otherwise returns y | ||
1/2 # float (0.5) | |||
1//2 # int (0) | |||
</source> | </source> | ||
Line 100: | Line 102: | ||
== Operations on Strings == | == Operations on Strings == | ||
<source lang="python"> | <source lang="python"> | ||
# formatted positional variable interpolation | # formatted positional variable interpolation (deprecated) | ||
'My name is %s, my age is %d' % (name, age) | 'My name is %s, my age is %d' % (name, age) | ||
# formatted dictionary-based variable interpolation | # formatted dictionary-based variable interpolation (deprecated) | ||
'My name is %(name)s, my age is %(age)d' % {'name': name, 'age', age} | 'My name is %(name)s, my age is %(age)d' % {'name': name, 'age', age} | ||
# number formats | # number formats (deprecated) | ||
"file_%03d.txt" % 2 # "file_002.txt" | "file_%03d.txt" % 2 # "file_002.txt" | ||
"5-day increase: %3.1f%%" % 2.6453 # "5-day increase: 2.6%" | "5-day increase: %3.1f%%" % 2.6453 # "5-day increase: 2.6%" | ||
# Python 3 string formatting | |||
"My name is {0}, my age is {1}".format(name, age) | |||
"My name is {name}, my age is {age}".format(name="Bill", age=28) | |||
date_info = {'year': "2020", 'month': "01", 'day': "01"} | |||
track_info = {'artist': "Beethoven", 'title': 'Symphony No 5'} | |||
filename = "{year}-{month}-{day}-{artist}-{title}.txt".format( | |||
**date_info, **track_info ) # '2020-01-01-Beethoven-Symphony No 5.txt' | |||
S = "abcdef" | S = "abcdef" | ||
S[2:4] # 'cd' substring | S[2:4] # 'cd' substring | ||
Line 183: | Line 192: | ||
'a' in x # True (in matches keys) | 'a' in x # True (in matches keys) | ||
x.copy() # {'a': 1, 'b': 2} (shallow copy) | x.copy() # {'a': 1, 'b': 2} (shallow copy) | ||
x.items() # [('a', 1), ('b', 2)] ( | x.items() # dict_items([('a', 1), ('b', 2)]) (can iterate with for) | ||
x.keys() # ['a', 'b'] ( | x.keys() # dict_keys(['a', 'b']) (can iterate with for) | ||
x.values() # [1, 2] ( | sorted(x.keys()) # ['a', 'b'] | ||
x.values() # dict_values([1, 2]) (can iterate with for) | |||
x['a'] # 1 | x['a'] # 1 | ||
x.get('a') # 1 | x.get('a') # 1 | ||
Line 196: | Line 206: | ||
x.pop('a') # x == {'b': 2} | x.pop('a') # x == {'b': 2} | ||
x.popitem() # ('a', 1), x == {'b':2} (item randomly selected) | x.popitem() # ('a', 1), x == {'b':2} (item randomly selected) | ||
</source> | </source> | ||
Line 231: | Line 240: | ||
<source lang="python"> | <source lang="python"> | ||
for x in range(5,25,5): | for x in range(5,25,5): | ||
print(x, end=" ") # 5 10 15 20 | print(x, end=" ") # 5 10 15 20 | ||
</source> | </source> |
Latest revision as of 19:11, 30 January 2020
What's new in Python 3
http://docs.python.org/3.0/whatsnew/3.0.html
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()
- To add a docstring to a function or class, add a single string as the first expression:
def myfunction():
"This is a very useful function"
...
print(myfunction.__doc__) # "This is a very useful function"
Object Types
None
bool
(True
orFalse
)int
,float
(int is arbitrarily large, float is accurate to 15 decimal places)str
(sequence of Unicode characters)bytes
(immutable),bytearray
(mutable)tuple
(immutable),list
(mutable)set
dict
- Others: dictionary views, iterators, type, function, classobj, instance
type(object) # returns the type of object
isinstance(1, int) # returns true
Implied Boolean
None, numeric 0, empty collection 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)
{ 'a', 'b', 'c' } # Set
{ '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
1/2 # float (0.5)
1//2 # int (0)
Operations on Sequences
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 (deprecated)
'My name is %s, my age is %d' % (name, age)
# formatted dictionary-based variable interpolation (deprecated)
'My name is %(name)s, my age is %(age)d' % {'name': name, 'age', age}
# number formats (deprecated)
"file_%03d.txt" % 2 # "file_002.txt"
"5-day increase: %3.1f%%" % 2.6453 # "5-day increase: 2.6%"
# Python 3 string formatting
"My name is {0}, my age is {1}".format(name, age)
"My name is {name}, my age is {age}".format(name="Bill", age=28)
date_info = {'year': "2020", 'month': "01", 'day': "01"}
track_info = {'artist': "Beethoven", 'title': 'Symphony No 5'}
filename = "{year}-{month}-{day}-{artist}-{title}.txt".format(
**date_info, **track_info ) # '2020-01-01-Beethoven-Symphony No 5.txt'
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 += [3,4] # x == [1, 2, 3, 4]
x.insert(1, 1.5) # x == [1, 1.5, 2]
x.remove(1) # x == [2]
del x[0] # 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)
Sets
x = {1, 2} # create literal set
y = set() # create empty set, {} denotes empty dict
x.add(5) # x == {1, 2, 5}
x.add(2) # x == {1, 2, 5}, only unique values get added
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() # dict_items([('a', 1), ('b', 2)]) (can iterate with for)
x.keys() # dict_keys(['a', 'b']) (can iterate with for)
sorted(x.keys()) # ['a', 'b']
x.values() # dict_values([1, 2]) (can iterate with for)
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)
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):
print(x, end=" ") # 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
.