!ls files/
Guido_van_Rossum.jpg who_uses_Python.png
python has relatively few keywords, simple structure, and a clearly defined syntax
Python lets you get more done with less code and less time
One of Python's greatest strengths is the bulk of the library is portable and cross-platform compatible on *nix and windows
Python interpreter lets you try out code right away in its interative mode
Python can run on a wide variety of platforms
Python is a dynamically typed langueages. Types are assigned at run-time
2+2
4
7/3 # Integer division returns the floor:
2
7/-3
-3
width = 20
height = 5*9
width * height
900
x = y = z = 0 # Zero x, y and z
x
0
y
0
z
0
#try to access an undefined variable
n
--------------------------------------------------------------------------- NameError Traceback (most recent call last) <ipython-input-9-0976a63577f7> in <module>() 1 #try to access an undefined variable ----> 2 n NameError: name 'n' is not defined
a = 1.5 + 0.5j # j is imaginary
a.real
a.imag
'spam eggs'
'spam eggs'
'doesn\'t'
"doesn't"
"doesn't" # 짝이 맞아야 함.
"doesn't"
'"yes"' # 겹쳐도 됨.
'"yes"'
'\"yes\"' # 이스케이프 써도 됨.
'"yes"'
'\"yes \'\"' # 두번 겹쳤을 때는 이스케이스 문자가 인식되지 않음.
'"yes \'"'
# 줄바꿈을 위해 \n 을 씀
# escape sequence : \n \t \r \0 \\ \' \"
hello = "This\nis\nhello "
print hello
This is hello
# """ 또는 '''을 사용하여 줄바꿈을 유지
hello = """This
is
hello"""
print hello
This is hello
# 문자열 앞에 r을 붙이면 raw문자열을 만든다.
# 이스케이스 문자가 적용되지 않음.
hello = r"This\nis\nhello "
print hello
This\nis\nhello
'str' 'ing' # This is ok
'string'
# strip() : 문자열 양쪽 공백을 모두 지움.
'str'.strip() + 'ing' #This is ok
'string'
print 'str'.strip() 'ing' # 문자열로 인식할 수 있음.
File "<ipython-input-21-536c70cca56b>", line 1 print 'str'.strip() 'ing' # 문자열로 인식할 수 있음. ^ SyntaxError: invalid syntax
word = "helpA"
word[4]
'A'
word[0:2]
'he'
word[2:4]
'lp'
word[:2]
'he'
word[2:]
'lpA'
word[0] = 'x'
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-28-d89b9f9f38d7> in <module>() ----> 1 word[0] = 'x' TypeError: 'str' object does not support item assignment
word[:1] = 'Splat'
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-29-f21641443054> in <module>() ----> 1 word[:1] = 'Splat' TypeError: 'str' object does not support item assignment
word[-1] # The last character
'A'
word[-2] # The last-but-one character
'p'
word[-2: ] # The last two characters
'pA'
word[:-2] # Everything except the last two characters
'hel'
a = ['spam', 'eggs', 100, 1234]
a
['spam', 'eggs', 100, 1234]
a[ : ]
['spam', 'eggs', 100, 1234]
a[2] = a[2] + 23
a
['spam', 'eggs', 123, 1234]
# Fibonacci series:
# the sum of two elements defines the next
a, b = 0, 1
while b < 10:
print b
a, b = b, a+b
1 1 2 3 5 8
# 입력받기
# 1. input : 정수로 받아 옴.
# val = input("입력: ")
# val
# 2. raw_input : 문자열로 받아 옴.
# val = raw_input("입력: ")
# val
# ** input 에 존재하는 변수명을 입력하면 변수로 인식 ** #
# test = 'hello'
# val = input("입력: ")
# val
x = int(raw_input("Please enter an integer: "))
Please enter an integer: 42
if x < 0:
x = 0
print 'Negative changed to zero'
elif x == 0:
print 'Zero'
elif x == 1:
print 'Single'
else:
print 'More'
More
# Measure some strings:
a = ['cat', 'window', 'defenestrate']
for x in a:
print x, ',' ,len(x)
cat , 3 window , 6 defenestrate , 12
# list operation
# 맨 앞에 새 요소 추가
# a.insert(0, 'new')
# 맨 뒤에 새 요소 추가
# a.append('new')
# 맨 앞의 요소 제거
# a.pop(0)
# 맨 마지막 요소 제거d
# a.pop()
# ** pop은 요소를 제거한 후 그 요소를 반환함.
for x in a[:]: # for x in a:
if len(x) > 6: a.insert(0,x)
a
['defenestrate', 'cat', 'window', 'defenestrate']
# python copy
# 1. shallow copy
# elements aren't copied
# list2 = list1[:]
# 2. deep copy
# import copy
# list2 = copy.deepcopy(list1)
colors1 = ['red', 'green']
colors2 = colors1
colors2 = ['yello', 'blue']
print colors1
['red', 'green']
colors1 = ['red', 'green']
colors2 = colors1
colors2 = 'blue'
colors1
['red', 'green']
list1 = ['a', 'b', 'c', 'd']
list2 = list1[:]
list2[1] = 'x'
print list2
['a', 'x', 'c', 'd']
print list1
['a', 'b', 'c', 'd']
# 위의 예제는 얕은 복사를 수행하지만
# 리스트가 서브리스트를 가질 때는 포인터 문제가 생긴다.
lst1 = ['a', 'b', ['ab', 'ba']]
lst2 = lst1[:]
lst2[0] = 'c' # shallow
lst2[2][1] = 'd'
print lst1 # deep
['a', 'b', ['ab', 'd']]
from copy import deepcopy
lst1 = ['a', 'b', ['ab', 'ba']]
lst2 = deepcopy(lst1)
lst2[2][1] = "d"
lst2[0] = "c";
print lst2
['c', 'b', ['ab', 'd']]
print lst1
['a', 'b', ['ab', 'ba']]
range(5, 10) # excep for las element
[5, 6, 7, 8, 9]
range(0, 10, 3) # 3을 더하면서
[0, 3, 6, 9]
# the else suite is executed after the for, but only if the for terminates normally (not by a break).for n in range (2,10):
# http://www.slideshare.net/helghareeb/python-tutorial-part-1?qid=75e5a1b1-d944-4c47-9cf3-d52e9db9ebd8&v=qf1&b=&from_search=2
for n in range(2,10):
for x in range(2, n):
if n % x ==0:
print n, 'quals', x, '*', n/x
break
else:
print n, 'is a prime number'
3 is a prime number 4 quals 2 * 2 5 is a prime number 5 is a prime number 5 is a prime number 6 quals 2 * 3 7 is a prime number 7 is a prime number 7 is a prime number 7 is a prime number 7 is a prime number 8 quals 2 * 4 9 is a prime number 9 quals 3 * 3
while True: pass
def fib(n):
""" Print a Fibonacci series up to n"""
a, b = 0, 1
while a<n:
print a,
a , b = b , a+b
fib(2000)
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597
def fib2 (n):
result = []
a, b = 0, 1
while a<n:
result.append(a)
a, b = b , a+b
return result
f100 = fib2(100)
f100
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
def ask_ok(prompt, retries = 4, complaint="Yes or no, please!"):
while True:
ok = raw_input(prompt)
if ok in ('y', 'ye', 'yes'):
return True
if ok in ('n','no', 'nop', 'nope'):
return False
retries = retries -1
if retries < 0:
raise IOError('refusenik user')
print complaint
ask_ok('test')
testyes
True
def parrot(voltage, state='a stiff', action='voom', type='Norwegian Blue'):
print voltage
print state
print action
print type
parrot(1000) # 1 positional argument
1000 a stiff voom Norwegian Blue
parrot(voltage=1000) # 1 keyword argument
1000 a stiff voom Norwegian Blue
parrot(voltage=1000000, action= 'VOMMM') # 2 keyword arguments
1000000 a stiff VOMMM Norwegian Blue
parrot('a million', 'bereft of life', 'jump') # 3positional argument
a million bereft of life jump Norwegian Blue
parrot('a thousand', state='pushing up the daisies') # 1 positional, 1 keyword
a thousand pushing up the daisies voom Norwegian Blue
# parrot()
# parrot(voltage=5.0, 'dead')
# parrot(110, voltage=220)
#parrot(actor='John')
#The *args and **kwargs is a common idiom to allow arbitrary number of arguments
def cheeseshop(kind, *arguments, **keywords):
print kind
for arg in arguments:
print arg
print "-" * 40
keys = sorted(keywords.keys())
for kw in keys:
print kw, ":", keywords[kw]
cheeseshop("This is kind", "no keyword1", "no keyword2",
bKeyword = "1",
aKeyword = "2",
cKeyword = "3")
This is kind no keyword1 no keyword2 ---------------------------------------- aKeyword : 2 bKeyword : 1 cKeyword : 3
함수를 한 줄만으로 만들 수 있게 함. lambda 인자 : 표현식
# 사용 후 바로 사라짐
(lambda x,y: x*y)(3,4)
12
# 인자값을 미리 지정하여 함수생성
multi = lambda x=3, y=4: x*y
multi()
12
# lambda
def make_incrementor(n):
#print n
#print x
return lambda x: x+ n
f = make_incrementor(42)
f(0)
42
f(2)
44
def my_function():
""" Do nothing"""
print "n"
pass
print my_function.__doc__
Do nothing
# example
a = [ 1,1, 2, 3, 7,4]
print a.count(1), a.count('a')
2 0
a.insert(1,0)
a
[1, 0, 1, 2, 3, 7, 4]
a.append(333)
a
[1, 0, 1, 2, 3, 7, 4, 333]
a.index(1)
0
a.remove(3)
a
[1, 0, 1, 2, 7, 4, 333]
a.reverse()
a
[333, 4, 7, 2, 1, 0, 1]
a.sort()
a
[0, 1, 1, 2, 4, 7, 333]
stack = [3, 4, 5]
stack.append(6)
stack.append(7)
stack
[3, 4, 5, 6, 7]
stack.pop()
7
stack
[3, 4, 5, 6]
from collections import deque
# Queue : 앞으로 삭제, 뒤로는 삽입
# Deque : 양방향 가능
queue = deque(["Kim", "Lim"])
queue.append("Lee")
queue.popleft()
'Kim'
queue
deque(['Lim', 'Lee'])
queue.appendleft("Park")
queue
deque(['Park', 'Lim', 'Lee'])
queue.pop()
'Lee'
filter(function, sequence)
return : 함수에서 정해진 내용의 반환값을 sequence형식으로 반환함.
def f(x) : return x%2 !=0 and x%3 !=0
filter(f, range(2, 25))
[5, 7, 11, 13, 17, 19, 23]
map(function, sequenc)
return : sequence를 모두 거치면서 함수의 내용을 수행, 반환 함
def cube(x) : return x*x*x
map(cube, range(1,11))
[1, 8, 27, 64, 125, 216, 343, 512, 729, 1000]
seq = range(8)
def add(x,y) : return x+y
map(add, seq, seq)
[0, 2, 4, 6, 8, 10, 12, 14]
def add(x,y) : return x+y
reduce(add, range(1,11))
55
squares = [ x**2 for x in range(10)]
squares
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
[(x,y) for x in [1,2,3] for y in [3,1,4] if x!=y]
[(1, 3), (1, 4), (2, 3), (2, 1), (2, 4), (3, 1), (3, 4)]
a = [-1, 2,3,4]
del a[0]
a
[2, 3, 4]
del a[1:2]
a
[2, 4]
t = 123, 321, 'hello'
t
(123, 321, 'hello')
u = t, (1,2,3,4,5) # Tuples may be nested
u
((123, 321, 'hello'), (1, 2, 3, 4, 5))
cate = 'hello', # note trailing comma
len(cate)
1
cate
('hello',)
union, intersection, difference, symmetric difference.
basket = ['apple', 'orange', 'apple', 'pear', 'orange', 'banana']
fruit = set(basket) # create a set without duplicates
fruit
{'apple', 'banana', 'orange', 'pear'}
'orange' in fruit # fast membership testing
True
# Demonstrate set operations on unique letters from two words
a = set('abracadabra')
b = set('alacazam')
a
{'a', 'b', 'c', 'd', 'r'}
a - b # letters in a but in b
{'b', 'd', 'r'}
a | b # letters in either a or b
{'a', 'b', 'c', 'd', 'l', 'm', 'r', 'z'}
a & b # letters in both a and b
{'a', 'c'}
a ^ b # letters in a or b but not both
{'b', 'd', 'l', 'm', 'r', 'z'}
key: value
score = {'Kim' : 100, 'Lim':20}
score['Lee'] = 90
score
{'Kim': 100, 'Lee': 90, 'Lim': 20}
score['Lim']
20
del score['Lim']
score
{'Kim': 100, 'Lee': 90}
score.keys()
['Lee', 'Kim']
'Kim' in score
True
dict( kim =100, lim=10, park = 30)
{'kim': 100, 'lim': 10, 'park': 30}
for i, v in enumerate(['tic', 'tac' ,'toe']):
print i,v
0 tic 1 tac 2 toe
questions = ['name', 'hobby']
answers = ['eunji', 'eating']
for q, a in zip(questions, answers):
print 'What is your {0}? It is {1}.'.format(q,a)
What is your name? It is eunji. What is your hobby? It is eating.
for i in reversed(xrange(1, 10, 2)):
print i
9 7 5 3 1
import fibo
fibo.fib(1000) # write
fibo.fib2(100) # return
1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987
[1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
fibo.__name__ # Within a module
# the module's name is available as the global variable __name__.
'fibo'
fib = fibo.fib
fib(500)
1 1 2 3 5 8 13 21 34 55 89 144 233 377
from fibo import fib, fib2
fib(500)
1 1 2 3 5 8 13 21 34 55 89 144 233 377
from fibo import *
fib(500)
1 1 2 3 5 8 13 21 34 55 89 144 233 377
import py_compile py_compile.compile("spam.py")
python -m compileall
파이은은 spam.py 파일이 있는 디렉토리에 spam.pyc 파일이 있다면 해당 파일이 spam 모듈의 바이트 컴파일된 버전이라고 가정한다.
만약 spam.py파일의 최종 수정 시각이 spam.pyc 파일에 기록되기 때문에, 둘이 다르다면 pyc 파일은 무시되어 py 파일만을 사용하게 된다.
pyc 파일은 플랫폼에 독립적이기 때문에 서로 다른 플랫폼에서 공유될 수 있다.
The built-in function dir() is used to find out which names a module defines.
import fibo, sys
dir(fibo)
['__builtins__', '__doc__', '__file__', '__name__', '__package__', 'fib', 'fib2']
dir(sys)
['__displayhook__', '__doc__', '__egginsert', '__excepthook__', '__name__', '__package__', '__plen', '__stderr__', '__stdin__', '__stdout__', '_clear_type_cache', '_current_frames', '_getframe', '_mercurial', 'api_version', 'argv', 'builtin_module_names', 'byteorder', 'call_tracing', 'callstats', 'copyright', 'displayhook', 'dont_write_bytecode', 'exc_clear', 'exc_info', 'exc_type', 'excepthook', 'exec_prefix', 'executable', 'exit', 'exitfunc', 'flags', 'float_info', 'float_repr_style', 'getcheckinterval', 'getdefaultencoding', 'getdlopenflags', 'getfilesystemencoding', 'getprofile', 'getrecursionlimit', 'getrefcount', 'getsizeof', 'gettrace', 'hexversion', 'last_traceback', 'last_type', 'last_value', 'long_info', 'maxint', 'maxsize', 'maxunicode', 'meta_path', 'modules', 'path', 'path_hooks', 'path_importer_cache', 'platform', 'prefix', 'ps1', 'ps2', 'ps3', 'py3kwarning', 'setcheckinterval', 'setdlopenflags', 'setprofile', 'setrecursionlimit', 'settrace', 'stderr', 'stdin', 'stdout', 'subversion', 'version', 'version_info', 'warnoptions']
str : 사용자가 보기 쉬운 형태로 보여줄 때 사용하는 것
repr: 시스템(python interpreter)이 해당 객체를 인식할 수 있는 공식적인 문자열로 나타내 줄 때 사용하는 것
str(1.0/7.0)
'0.142857142857'
repr(1.0/7.0)
'0.14285714285714285'
for x in range(1,11):
print repr(x).rjust(2), repr(x*x).rjust(3),
print repr(x*x*x).rjust(4)
1 1 1 2 4 8 3 9 27 4 16 64 5 25 125 6 36 216 7 49 343 8 64 512 9 81 729 10 100 1000
# rjust : 오른쪽 정렬
# ljust : 왼쪽 정렬
a = "123"
print a.rjust(10)
123
print a.rjust(10,'#')
#######123
for x in range(1,11):
print '{0:2d} {2:4d} {1:3d}'.format(x, x*x, x*x*x)
1 1 1 2 8 4 3 27 9 4 64 16 5 125 25 6 216 36 7 343 49 8 512 64 9 729 81 10 1000 100
f = open('./testFile', 'r') # write : w , bothe w+
print f
<open file './testFile', mode 'r' at 0x7fa068255540>
f.read() # 전체를 읽음.
"(dp0\nS'lim'\np1\nI20\nsS'kim'\np2\nI80\ns."
f.read() # f.readlines()
''
f = open('./testFile', 'r')
f.readline()
'(dp0\n'
f.readline()
"S'lim'\n"
f.readline()
'p1\n'
f.readline()
'I20\n'
# alternative method
f = open('./testFile', 'r')
for line in f:
print line,
(dp0 S'lim' p1 I20 sS'kim' p2 I80 s.
# Write to file
f = open('./testFile', 'w+')
f.write('This is a test\n')
f.readlines()
[]
f.close()
#f.read()
파이썬에서 만들어는는 것은 뭐든지 다 파일에 적을 수 있다.
import pickle
f = open('./testFile2','w')
users = {'kim':80, 'lim':20}
pickle.dump(users, f)
f.close()
f = open('./testFile2','r')
a = pickle.load(f)
print a
{'lim': 20, 'kim': 80}
#while True: print 'Hello world'
while True print 'Hello world'
File "<ipython-input-1-b4e7f45d347e>", line 2 while True print 'Hello world' ^ SyntaxError: invalid syntax
10 * (1/0)
--------------------------------------------------------------------------- ZeroDivisionError Traceback (most recent call last) <ipython-input-2-9ce172bd90a7> in <module>() ----> 1 10 * (1/0) ZeroDivisionError: integer division or modulo by zero
4 + spam*3
--------------------------------------------------------------------------- NameError Traceback (most recent call last) <ipython-input-3-6b1dfe582d2e> in <module>() ----> 1 4 + spam*3 NameError: name 'spam' is not defined
'2' +2
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-4-c84fbe601d35> in <module>() ----> 1 '2' +2 TypeError: cannot concatenate 'str' and 'int' objects
while True:
try:
x = int(raw_input("Please enter a number: "))
break
except ValueError:
print "That was no valid number. Try again..."
Please enter a number: lis That was no valid number. Try again... Please enter a number: 1
break 로 끝나지 않으면, else 아래의 코드를 실행시키다.
import sys
for arg in sys.argv[1:] :
try:
f = open(arg, 'r')
except IOError:
print 'cannot open',arg
else :
print arg, 'has', len(f.readlines()), 'lines'
f.close()
cannot open -f /home/lim/.ipython/profile_default/security/kernel-b9f480b6-e7a4-499e-bfe6-c536d5bc0f3a.json has 11 lines cannot open --profile-dir cannot open /home/lim/.ipython/profile_default
def this_fails():
x = 1/0
try:
this_fails()
except ZeroDivisionError as detail:
print 'Handling run-time error: ', detail
Handling run-time error: integer division or modulo by zero
raise NameError('HiThere')
--------------------------------------------------------------------------- NameError Traceback (most recent call last) <ipython-input-9-93385ba972b1> in <module>() ----> 1 raise NameError('HiThere') NameError: HiThere