python usage (5-minute-summary)
DESCRIPTION
TRANSCRIPT
Python Usage (5 minute summary)
Ohgyun Ahn
Variables
» n = 10 » n
10 » type(n)
<type 'int'>
» str = 'string' » type(str)
<type 'str'>
» int_from_string = int('10') » int_from_string
10
Floats
» f = 2.5 » type(f)
<type 'float'>
» float_from_int = float(n) » float_from_int
10.0
» 15 / 2
7 » 15 / 2.0
7.5
Bools
» b = True » type(b)
<type 'bool'>
» string_from_bool = str(b)
'True'
» bool('True')
True » bool('False')
True » bool(-1)
True
Bools
» bool(None) # None is python NULL value
False » bool(0) # false when zero
False » bool('') # false when empty string
False » bool([]) # false when length is zero
False » bool({})
False
Comments
# This is a single line comment.
'''
This is
a multi-line
comments
'''
Strings
» my_string = "This is string" » my_string2 = 'This is string'
» formatted = "Alphabet: %s, %s" % ("A", "Z") » formatted
'Alphabet: A, Z'
» print 'abc'
abc
» print 'a', 'b', 'c'
a b c
» print 'my name is %s' % ('foo')
my name is foo
Lists
» my_list = [1, 2, 3] » my_list
[1, 2, 3]
» my_list[2]
3
» my_list[2] = 4 » my_list
[1, 2, 4]
» my_list.index(4) # ValueError if not exist
2
Lists
» my_list.append(5) » my_list
[1, 2, 4, 5]
» my_list.insert(2, 3) # insert(index, value) » my_list
[1, 2, 3, 4, 5]
» my_list + [7, 8]
[1, 2, 3, 4, 5, 7, 8] » my_list
[1, 2, 3, 4, 5]
Lists
» my_list.pop(2) # pop(index)
3 » my_list
[1, 2, 4, 5]
» my_list.remove(5) # remove(value) » my_list
[1, 2, 4]
» my_list.reverse() » my_list
[4, 2, 1]
Lists
» sorted(my_list) # get sorted list
[1, 2, 4] » my_list
[4, 2, 1]
» my_list.sort() # sort original list » my_list
[1, 2, 4]
Conditions
» n = 10
» if n > 5 and n < 15: # (and | or | not | in) » print 'good!' » elif n < 0: » print 'nagative!' » else: » print 'bad!'
good
For Loops
» my_list = [1, 2, 3, 4] » for item in my_list: » print item,
1 2 3 4
» my_string = 'abcd' » for letter in my_string: » print letter,
a b c d
» my_dict = {'a': 'aaa', 'b': 'bbb'} » for key in my_dict: » print key,
a b
For Loops
» for item in my_list: » print item, » else: » print 'done'
1 2 3 4 done
» for item in my_list: » if item > 2: break » else: print item, » else: # when for loop terminate normally (not by break)
» print 'done'
1 2
While Loops
» count = 0
» while count < 5: » print count, » count += 1 » else: » print 'done'
0 1 2 3 4 done
List Comprehensions
» my_list = [1, 2, 3, 4, 5, 6, 7, 8]
» # [item for item in List if Condition] » even_list = [n for n in my_list if n%2 == 0] » even_list
[2, 4, 6, 8]
» even_squared_list = \ [n**2 for n in my_list if n%2 == 0]
» even_squared_list
[4, 16, 36, 64]
Range
» range(1, 4) # range(start, stop, step)
[1, 2, 3] » range(4)
[0, 1, 2, 3] » range(-1, 4)
[-1, 1, 2, 3] » range(1, 4, 2)
[1, 3]
» [i for i in range(4)]
[0, 1, 2, 3] » for i in range(4): print str(i),
0 1 2 3
Slice
» my_list = range(1, 9) » my_list
[1, 2, 3, 4, 5, 6, 7, 8]
» my_list[0:3] # [start:end:stride]
[1, 2, 3] » my_list[:2]
[1, 2] » my_list[-2:]
[7, 8] » my_list[:-1]
[1, 2, 3, 4, 5, 6, 7] » my_list[::2]
[1, 3, 5, 7]
Slice
» my_list[::-1] # reverse
[8, 7, 6, 5, 4, 3, 2, 1]
» my_string = "Apple" » my_string[::-1]
"elppA"
» x_string = "XXXHXeXlXlXoXXX" » x_string[3:-3:2]
"Hello"
Tuples
» my_tuple = (1, 2, 3, 4) » my_tuple[2]
3 » my_tuple[2] = 3 # tuples are immutable
TypeError
» my_list = [1, 2, 3, 4] » tuple_from_list = tuple(my_list) » tuple_from_list
(1, 2, 3, 4)
» list_from_tuple = list(my_tuple) » list_from_tuple
[1, 2, 3, 4]
Sets
» my_set = {2, 1, 2, 3, 4, 2, 3, 3, 4} » my_set # unique but unordered
set([1, 2, 3, 4]) » type(my_set)
<type 'set'>
» dup_list = [1, 1, 2, 2, 3, 3, 4, 4, 4] » set_from_list = set(dup_list) » set_from_list
set([1, 2, 3, 4])
» list_from_set = list(my_set) » list_from_set
[1, 2, 3, 4]
Dictionaries
» my_dict = {'a': 'aaa', 'b': 'bbb'} » my_dict
{'a': 'aaa', 'b': 'bbb'} » type(my_dict)
<type 'dict'> » dict(a=111, b=222)
{'a': 111, 'b': 222}
» my_dict.items() # result is array of tuples
[('a', 'aaa'), ('b', 'bbb')] » my_dict.keys()
['a', 'b'] » my_dict.values()
['aaa', 'bbb']
Dictionaries
» my_dict['a']
'aaa'
» my_dict.get('a')
'aaa'
» my_dict['a'] = 'AAA' » my_dict
{'a': 'AAA', 'b': 'bbb'}
» my_dict.update({'a': 'aaa', 'c': 'ccc'}) » my_dict
{'a': 'aaa', 'b': 'bbb', 'c': 'ccc'}
Functions
» def add_one(a, b): » ''' Here's doc string ''' » c = a + b » return c
» add_one(3, 5)
8
» def add_many(*args): » print args # args is tuple of arguments » pass # pass here, does nothing
» add_many(1, 2, 3)
(1, 2, 3)
Lambda Functions
» my_list = range(1, 9)
» my_lambda = lambda n: n%2 == 0 » # lambda is an anonymous function. » # my_lambda is same with below: » # def (n): » # return n%2 == 0 » type(my_lambda)
<type 'function'>
» # filter my_list using lambda » filter(my_lambda, my_list)
[2, 4, 6, 8]
Classes
» class Shape(object): » member_var = "I'm a member of class" » » def __init__(self): # constructor » pass
» type(Shape)
<type 'type'>
» class Rect(Shape): # inherit Shape » pass
» r = Rect() # create instance » type(r)
<class '__main__.Shape'>
Modules
» # A module is a file containing » # Python definitions and statements. » # The file name is the module name » # with the suffix .py appended.
» __name__ # name of current module
'__main__'
» math
NameError » import math # import math module » math
<module 'math' from ...>
Modules
[my_module.py]
def add_one(a, b):
return a + b
[main] » import my_module » dir()
[ .. , 'my_module'] » dir(my_module)
[ .., 'add_one'] » my_module.add_one(2, 3)
5