python usage (5-minute-summary)

29
Python Usage (5 minute summary) Ohgyun Ahn

Upload: ohgyun-ahn

Post on 01-Nov-2014

2.451 views

Category:

Documents


0 download

DESCRIPTION

 

TRANSCRIPT

Page 1: Python Usage (5-minute-summary)

Python Usage (5 minute summary)

Ohgyun Ahn

Page 2: Python Usage (5-minute-summary)

Variables

» n = 10 » n

10 » type(n)

<type 'int'>

» str = 'string' » type(str)

<type 'str'>

» int_from_string = int('10') » int_from_string

10

Page 3: Python Usage (5-minute-summary)

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

Page 4: Python Usage (5-minute-summary)

Bools

» b = True » type(b)

<type 'bool'>

» string_from_bool = str(b)

'True'

» bool('True')

True » bool('False')

True » bool(-1)

True

Page 5: Python Usage (5-minute-summary)

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

Page 6: Python Usage (5-minute-summary)

Comments

# This is a single line comment.

'''

This is

a multi-line

comments

'''

Page 7: Python Usage (5-minute-summary)

Strings

» my_string = "This is string" » my_string2 = 'This is string'

» formatted = "Alphabet: %s, %s" % ("A", "Z") » formatted

'Alphabet: A, Z'

Page 8: Python Usage (5-minute-summary)

Print

» print 'abc'

abc

» print 'a', 'b', 'c'

a b c

» print 'my name is %s' % ('foo')

my name is foo

Page 9: Python Usage (5-minute-summary)

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

Page 10: Python Usage (5-minute-summary)

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]

Page 11: Python Usage (5-minute-summary)

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]

Page 12: Python Usage (5-minute-summary)

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]

Page 13: Python Usage (5-minute-summary)

Conditions

» n = 10

» if n > 5 and n < 15: # (and | or | not | in) » print 'good!' » elif n < 0: » print 'nagative!' » else: » print 'bad!'

good

Page 14: Python Usage (5-minute-summary)

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

Page 15: Python Usage (5-minute-summary)

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

Page 16: Python Usage (5-minute-summary)

While Loops

» count = 0

» while count < 5: » print count, » count += 1 » else: » print 'done'

0 1 2 3 4 done

Page 17: Python Usage (5-minute-summary)

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]

Page 18: Python Usage (5-minute-summary)

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

Page 19: Python Usage (5-minute-summary)

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]

Page 20: Python Usage (5-minute-summary)

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"

Page 21: Python Usage (5-minute-summary)

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]

Page 22: Python Usage (5-minute-summary)

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]

Page 23: Python Usage (5-minute-summary)

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']

Page 24: Python Usage (5-minute-summary)

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'}

Page 25: Python Usage (5-minute-summary)

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)

Page 26: Python Usage (5-minute-summary)

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]

Page 27: Python Usage (5-minute-summary)

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'>

Page 28: Python Usage (5-minute-summary)

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 ...>

Page 29: Python Usage (5-minute-summary)

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