티스토리 뷰



A Byte Of Python 번역본을 보고 공부를 해보자 인터넷을 통한 지식의 공유 정신을 통하여 오픈 소스, 오픈 콘텐즈와 오픈 교육이 활성화 될 수 있었다. 삶에 있어 성공이라고 하는 것은 재능과 요행보다는 집중력과 참을성에 달려 있습니다.(Success in life is a matter not so much of talent and opportunity as of concentration and perseverance.-C.W.Wendte) 파이썬이라는 이름의 유래는 파이쎤의 창시자 귀도 반 로섬(Guido van Rossum)이 BBC에서 방영되던 "Monty Python's Flying Circus"라는 TV 프로그램의 이름을 따서 지었습니다.

In [8]:
# 첫번째 python 프로그램
print("Helllo, World!")
Helllo, World!

작성된 프로그램을 저장(예 : hello.py)하고 다시 수행하고 싶을 경우 아래와 같이 한다.(확장자를 반드시 py로 해야 한다.) $ python hello.py

In [13]:
# 파이썬의 함수나 명령에 대한 도움말이 필요할 경우 help를 사용한다.
help(format)
Help on built-in function format in module builtins:

format(...)
    format(value[, format_spec]) -> string
    
    Returns value.__format__(format_spec)
    format_spec defaults to ""

In [ ]:
# format 함수를 통한 출력 형태의 변경
print('{0:_^10}'.format("Hello")+"\n")
# 숫자를 10지리 문자로 변환하기(99억까지 숫자 인덱스로 사용)
'{0:010d}'.format(1)

주석은 "#"을 통하여 작성한다. 지금은 문제가 되지 않겠지만 6개월 후에 다시 소스를 보았을때 주석이 없다면 작성한 사람이라도 이해가 어려운 경우가 많다.

In [55]:
# coding utf-8

문자열을 표현하는 방법으로 작은 따옴표(')와 큰 따옴표(") 둘다 사용이 가능하지만 What's your name?과 같이 내부에 작은 따움표가(') 있는 경우 큰 따움표(") 해야 오류가 발생하지 않는다. 반대의 경우 the " is big quotation는 작은따음표(') 사용해야 오류가 발생하지 않는다. 두개(small('), big("))가 같이 있는 경우는 (""") 혹은 (''') 사용한다.

다른 방법은 Escape 문자()을 사용하는 것도 가능하다 긴문장을 연결시킬때도 Escape 문자() 사용하면 편리하다.

순 문자열(Raw Character)은 문자열에 포함된 이스케이프 문자를 처리하지 않고 있는 그대로를 출력하고 싶을때 사용합니다.(정규식에서 많이 활용) 예) print(r"줄바꿈 문자는 \n")

In [5]:
print("What's your name?")
print('What\'s your name?') # Escape 문자 사용
print('the " is big quotation')
print("""It's very Important, diffence of small('), big(") quotation""")
print('''It's very Important, diffence of small('), big(") quotation''')
print("soook is \
wife of zedo \
won is son of zedo")
print(r"줄바꿈 문자는 \n")
What's your name?
What's your name?
the " is big quotation
It's very Important, diffence of small('), big(") quotation
It's very Important, diffence of small('), big(") quotation
soook is wife of zedo won is son of zedo
줄바꿈 문자는 \n

문자열에 매개변수를 주어 출력하는 것을 문자열 포맷팅이라 합니다. 문자열을 "+"을 통해 만들 수도 있으나 정수가 있는 경우 매번 String으로 변환해야 하고, 가독성이 떨이지므로 format을 반드시 활용한다.

In [75]:
age=20
name="Sook"
print("{0}의 나이는 {1}살 입니다.".format(name, age))
print("왜 {0}은 python과 놀지 않나요?".format(name))
# 아래와 같이 바꿀수도 있지만, 정수는 String 변환하고 가독성 떨어짐
print(name+"의 나이는 "+str(age)+"살 입니다.")
# 문자열 포맷팅 사용시 "{숫자}"에서  숫자는 생략 가능함
print("{}의 나이는 {}살 입니다.".format(name, age))
# {숫자} 대신에 {변수} 대입이 가능합니다.
print("{name}은 {what}을 좋아합니다.".format(name="zedo", what="python"))
Sook의 나이는 20살 입니다.
왜 Sook은 python과 놀지 않나요?
Sook의 나이는 20살 입니다.
Sook의 나이는 20살 입니다.
zedo은 python을 좋아합니다.

기본 데이터형은 정수(integer), 실수(Floating), 문자열(String)이며 확장형으로 튜플(Tuple), 리스트(List), 사전(Dictory)을 가진다. 블린(Boolean)형도 있으며 True, False 값을 가진다.

In [2]:
print(12345)  # 정수
print(3.141592) # 실수
print("Hello, World!") # 문자열
print((1,2,3,4,5)) # 튜플(내부 데이터 변경 불가)
print(["one", "two", "three", "four"]) # 리스트
print({1:"one", 2:"two", 3:"three", 4:"four"}) #사전
12345
3.141592
Hello, World!
(1, 2, 3, 4, 5)
['one', 'two', 'three', 'four']
{1: 'one', 2: 'two', 3: 'three', 4: 'four'}

파이썬에서는 들여쓰기(Indentation)이 무지 중요하다. 이것때문에 코딩 실수가 많이 발생한다. 파이썬에서는 공식적으로 Tab을 사용하기 보다는 공백 4개 넣기를 추천한다.

In [6]:
print("park")
 print("jae")
    
  File "<ipython-input-6-14f9455c5c5a>", line 2
    print("jae")
    ^
IndentationError: unexpected indent


제어문(Control Statement)을 공부하자

In [4]:
number = 23
running = True
while running :
    guess = int(input("자 내가 생각하는 숫자는 무엇일까요? : "))
    if guess == number :
        print("축하합니다. 맞추었어요")
        running = False
    elif guess < number :
        print("좀 더 큰 수를 넣어 보세요")        
    else :
        print("좀 더 작은 수를 넣어 보세요")        
print("끝")    
자 내가 생각하는 숫자는 무엇일까요? : 32
좀 더 작은 수를 넣어 보세요
자 내가 생각하는 숫자는 무엇일까요? : 23
축하합니다. 맞추었어요
끝
In [10]:
# For 루프 사용 예시
for i in range(1,5) : 
    print(i)
else : 
    print("The for loop is over")
    
0
1
2
3
4
The for loop is over
In [11]:
# 위의 "else :" 구문이 없어도 된다.
for i in range(1,5) : 
    print(i)
print("The for loop is over")
1
2
3
4
The for loop is over
In [16]:
# range 함수를 사용하면 List를 반환한다.
a=range(1,3)
for i in a :
    print(i)
# range 함수에서 세번째 인수에 증감수를 넣을 수 있다.(기본 1)
a=range(1,5,2)
for i in a :
    print(i)
    
1
2
1
3

Loop를 중지하기 위하여 break를 사용할 수 있고 다음 반복으로 바로 넣어가지 위해 continue을 사용할 수도 있다.

In [19]:
while True :
    s = input("Quit 입력하면 중단됩니다.")
    if s == "Quit" :
        break
    print("입력문자열 길이 : {0}".format(len(s)))
print("끝")
Quit 입력하면 중단됩니다.a
입력문자열 길이 : 1
Quit 입력하면 중단됩니다.park jae do
입력문자열 길이 : 11
Quit 입력하면 중단됩니다.Quit
끝
In [20]:
while True :
    s = input("Quit 입력하면 중단됩니다.")
    if s == "Quit" :
        break
    if len(s) < 3:
        print("문자열이 작아요")
        continue
    print("입력문자열 길이 : {0}".format(len(s)))
print("끝")
Quit 입력하면 중단됩니다.sok
입력문자열 길이 : 3
Quit 입력하면 중단됩니다.Quit
끝

이제 함수에 대하여 공부해 보자

프로그램에서 재사용 목적으로 사용되며 def로 정의한다

In [22]:
def say_hello() :
    print("hello, world")
say_hello()
hello, world

매개변수를 넘길 수 있도록 함수를 만들어 보자

In [25]:
def print_max(a,b) : 
    if a > b :
        print("{0} is maximum".format(a))
    elif a==b :
        print("{0}, {1} is equal".format(a,b))
    else :
        print("{0} is maximum".format(b))
print_max(3,4)
print_max(3,3)
print_max(5,4)
4 is maximum
3, 3 is equal
5 is maximum

전역변수를 사용하기 위해서는 global이란 키워드 사용한다.

In [2]:
#  grobal 을 함수내에서 사용하는 것은 좋지 못하다.
x=50
def func() :
    global x
    print("x is {0}".format(x))
    x=2
    print("x is {0}".format(x))
func()
print("x is {0}".format(x))
x is 50
x is 2
x is 2

함수의 매개변수에 기본값을 지정 가능하다.

매개 변수 목록에서 마지막에 있는 매개 변수들에만 기본 인수값을 지정해 줄 수 있습니다

def func(a, b=5) 정상 동작, def func(a=5, b) 오류 발생

In [4]:
def say(message, times=1) :
    print(message * times)
say("Hello")
say("World", 5)
Hello
WorldWorldWorldWorldWorld

키위드 인수(Keyword parameter)를 통하여 함수를 호출할때 값을 직접 지정 가능

In [6]:
def func(a, b=5, c=10) :
    print("a is {0}, b is {1}, c is {2}".format(a,b,c))
func(3,7)
func(25, c=24)
func(c=50, a=100)
a is 3, b is 7, c is 10
a is 25, b is 5, c is 24
a is 100, b is 5, c is 50

VarArgs 매개변수를 통해 임의(Variable)의 갯수의 매개변수(Arguments)를 지정 가능함

전달된 매개 변수는 numbers은 튜플로 *keyworks는 사전으로 전달됨

In [11]:
def total(inital=0, *numbers, **keywords) :
    count = inital
    for n in numbers :
        count += n
        print(n)
    for k in keywords :
        count += keywords[k]
        print(k)
    return count
print(total(0, 1, 2, 3, vegetable=50, fruits=100))
1
2
3
vegetable
fruits
156

아무것도 하지 않는 함수를 사용하고 싶을때는 pass를 사용한다.

In [12]:
def do_not_thing() :
    pass
do_not_thing()

DocString은 설명(Documentation) 문자열(String)) 기능을 이야기 함

모듈과 클래스에서 사용 가능하며 첫째줄의 첫문자는 대문자로, 마지막 문자는 마침표로 끝나며, 두번째 줄은 비워 두고, 세번째 줄부터는 이것이 어떤 기능을 하는지에 대해 상세하게 작성함

help() 함수에서 특정 모듈의 도움말이 DocString을 통하여 제공됨

In [14]:
def print_max(x, y) :
    """print_max(x, y)는 두 숫자 중에 끝 수를 출력함.
    
    두개의 숫자는 반드시 정수여야함."""
    x = int(x)
    y = int(y)
    if x > y :
        print("{0} is maximum".format(x))
    else :
        print("{0} is maximum".format(y))
print_max(3,5)
print(print_max.__doc__)
5 is maximum
print_max(x, y)는 두 숫자 중에 끝 수를 출력함.
    
    두개의 숫자는 반드시 정수여야함.

import 명령을 사용하여 이미 작성됨 모듈을 사용할 수 있음

from import 명령을 사용하여 간단하게 사용 가능하지만 권장하지 않음

In [16]:
import sys
for i in sys.argv :
    print(i)
print("\n\nThe PYTHONPATH is {0}\n".format(sys.path))
C:\Anaconda3\lib\site-packages\IPython\kernel\__main__.py
-f
C:\Users\zedo\.ipython\profile_default\security\kernel-7a4026dd-ce16-40e7-8ff4-cf5bac45311e.json
--profile-dir
C:\Users\zedo\.ipython\profile_default


The PYTHONPATH is ['', 'C:\\Work', 'C:\\Anaconda3\\python34.zip', 'C:\\Anaconda3\\DLLs', 'C:\\Anaconda3\\lib', 'C:\\Anaconda3', 'C:\\Anaconda3\\lib\\site-packages', 'C:\\Anaconda3\\lib\\site-packages\\Sphinx-1.3.1-py3.4.egg', 'C:\\Anaconda3\\lib\\site-packages\\cryptography-0.9.1-py3.4-win32.egg', 'C:\\Anaconda3\\lib\\site-packages\\win32', 'C:\\Anaconda3\\lib\\site-packages\\win32\\lib', 'C:\\Anaconda3\\lib\\site-packages\\Pythonwin', 'C:\\Anaconda3\\lib\\site-packages\\setuptools-18.0.1-py3.4.egg', 'C:\\Anaconda3\\lib\\site-packages\\IPython\\extensions']

In [40]:
# 권장하지는 않지만 사용 가능함
from math import sqrt
print(sqrt(10))
3.1622776601683795
In [21]:
%matplotlib inline
import pylab as pl
import numpy as np
# -3.14159와 3.14159 사이에 256개의 숫자를 발생시켜, Sine, Cosine 값을 구하고 
# 그래프로 보여줌
X = np.linspace(-np.pi, np.pi, 256, endpoint=True)
C, S = np.cos(X), np.sin(X)
pl.plot(X, C)
pl.plot(X, S)
pl.show()
In [22]:
%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
# 복소수 자표계를 표현함
limit=4
s=[2+2j, 3+2j, 1.75+1j, 2+1j, 2.25+1j, 2.5+1j, 2.75+1j, 3+1j, 3.25+1j]
for x in range(len(s)) :
    plt.plot(s[x].real, s[x].imag, 'ro-', label='complex')
    ##  plt.plot([0,s[x].real], [0, s[x].imag])
plt.xlim(-limit,limit)
plt.ylim(-limit,limit)
plt.ylabel('Imaginary')
plt.xlabel('Real')  
plt.grid(True)
plt.show()
In [23]:
# 문자열을 공백을 기준으로 잘라서 list로 만들고 다시 enumerate로 변환
def makeInverseIndex(strlist) :
    return {x:y for (x,y) in enumerate(list(strlist.split()))}
makeInverseIndex("Ask not what you can do for your country")
Out[23]:
{0: 'Ask',
 1: 'not',
 2: 'what',
 3: 'you',
 4: 'can',
 5: 'do',
 6: 'for',
 7: 'your',
 8: 'country'}
In [27]:
list("Ask not what you can do for your country".split())
Out[27]:
['Ask', 'not', 'what', 'you', 'can', 'do', 'for', 'your', 'country']
In [32]:
%matplotlib inline
import matplotlib.pyplot as plt
import numpy as np
import pylab as plt
import csv as csv
import pandas as pd
# R의 dprep 팩키지의 autompg 데이터셋을 활용한다.
#  write.table(autompg, "c:/work/autompg.csv", sep=",",col.names = TRUE, row.names=FALSE)
readdata = csv.reader(open('C:/Work/autompg.csv'))
data=[]
for row in readdata :
    data.append(row)
Header=data[0]
data.pop(0)
cars = pd.DataFrame(data, columns=Header)
plt.plot(cars.mpg, cars.displacement, 'ro', label='cars')
plt.ylabel('displ')
plt.xlabel('mpg')
plt.show()
In [37]:
# CSV file reader
import csv
cars=[]
f = open('c:/work/autompg.csv', 'r')
csvReader  = csv.reader(f)
for row in csvReader :
   cars.append(row)
# header와 데이터 출력하기
print(cars[0])
print(cars[len(cars)-1])
f.close()
['mpg', 'cylinders', 'displacement', 'horsepower', 'weight', 'acceleration', 'modelyear', 'maker']
['31', '4', '119', '82', '2720', '19.4', '82', '1']

파이션에는 4개의 자료 구조가 있음

리스트(List []), 튜플(Tuple ()), 사전(Dictionary {}), 집합(Set)

In [44]:
# This is my shopping list
shoplist = ['apple', 'mango', 'carrot', 'banana']
print('I have', len(shoplist), 'items to purchase.')
print('These items are:')
for item in shoplist:
    print(item)
print('\nI also have to buy rice.')
shoplist.append('rice')
print('My shopping list is now', shoplist)
print('I will sort my list now')
shoplist.sort()
print('Sorted shopping list is', shoplist)
print('The first item I will buy is', shoplist[0])
olditem = shoplist[0]
del shoplist[0]
print('I bought the', olditem)
print('My shopping list is now', shoplist)
I have 4 items to purchase.
These items are:
apple
mango
carrot
banana

I also have to buy rice.
My shopping list is now ['apple', 'mango', 'carrot', 'banana', 'rice']
I will sort my list now
Sorted shopping list is ['apple', 'banana', 'carrot', 'mango', 'rice']
The first item I will buy is apple
I bought the apple
My shopping list is now ['banana', 'carrot', 'mango', 'rice']
In [49]:
# 튜플의 예제
zoo = ('python', 'elephant', 'penguin')
print('Number of animals in the zoo is', len(zoo))
new_zoo =('monkey', 'camel', zoo)
print(new_zoo)
print('Number of cages in the new zoo is', len(new_zoo))
print('All animals in new zoo are', new_zoo)
print('Animals brought from old zoo are', new_zoo[2])
print('Last animal brought from old zoo is', new_zoo[2][2])
print('Number of animals in the new zoo is', \
    len(new_zoo)-1+len(new_zoo[2]))
Number of animals in the zoo is 3
('monkey', 'camel', ('python', 'elephant', 'penguin'))
Number of cages in the new zoo is 3
All animals in new zoo are ('monkey', 'camel', ('python', 'elephant', 'penguin'))
Animals brought from old zoo are ('python', 'elephant', 'penguin')
Last animal brought from old zoo is penguin
Number of animals in the new zoo is 5
In [51]:
# List 예제
ab = {  'Swaroop'   : 'swaroop@swaroopch.com',
        'Larry'     : 'larry@wall.org',
        'Matsumoto' : 'matz@ruby-lang.org',
        'Spammer'   : 'spammer@hotmail.com'
    }
print("Swaroop's address is", ab['Swaroop'])
# Deleting a key-value pair
del ab['Spammer']
print('\nThere are {} contacts in the address-book\n'.format(len(ab)))
for name, address in ab.items():
    print('Contact {} at {}'.format(name, address))
# Adding a key-value pair
ab['Guido'] = 'guido@python.org'
if 'Guido' in ab:
    print("\nGuido's address is", ab['Guido'])
    
Swaroop's address is swaroop@swaroopch.com

There are 3 contacts in the address-book

Contact Larry at larry@wall.org
Contact Matsumoto at matz@ruby-lang.org
Contact Swaroop at swaroop@swaroopch.com

Guido's address is guido@python.org

열거형을 통해 리스트, 튜플, 문자열에서 인덱싱 연상을 수행한다.

In [60]:
shoplist=["ppk", "k-2", "walther", "m16", "m203"]
print("Item 0 is {0}".format(shoplist[0]))
print("Item -1 is {0}".format(shoplist[-1])) # 마지막 향목을 가져옴
print("Item -2 is {0}".format(shoplist[-2])) # 마지막 항목 앞의 것을 가져옴
# 리스트를 구분하기(Slice(:))
print("Item 1 to 3 is ", shoplist[1:3])
print("Item 1 to end is ", shoplist[1:])
print("Item 1 to -1 is ", shoplist[1:-1])
print("Item start to end is ", shoplist[:])
Item 0 is ppk
Item -1 is m203
Item -2 is m16
Item 1 to 3 is  ['k-2', 'walther']
Item 1 to end is  ['k-2', 'walther', 'm16', 'm203']
Item 1 to -1 is  ['k-2', 'walther', 'm16']
Item start to end is  ['ppk', 'k-2', 'walther', 'm16', 'm203']

슬라이스(:) 연산에 스템(Step)을 넣을 수 있음(기본값 1)

In [64]:
shoplist=["ppk", "k-2", "walther", "m16", "m203"]
print("Item start to end(step 1) is ", shoplist[::1])
print("Item start to end(step 2) is ", shoplist[::2])
print("Item start to end(step -1(Reverse)) is ", shoplist[::-1])
Item start to end(step 1) is  ['ppk', 'k-2', 'walther', 'm16', 'm203']
Item start to end(step 2) is  ['ppk', 'walther', 'm203']
Item start to end(step -1(Reverse)) is  ['m203', 'm16', 'walther', 'k-2', 'ppk']

집합은 set() 함수를 통해 구현하며 값은 중복되지 않는다.

In [70]:
shoplist=set(["ppk", "k-2", "walther", "m16", "m203", "m16"])
print("shoping List is ", shoplist) # 중복 되지 않는다.
sooklist = shoplist.copy()
sooklist.add("k201")
print("sook shoping List is ", sooklist) 
sooklist.remove("ppk")
print("the zedo & sook same things are ", shoplist & sooklist) #  교집함
print("the zedo & sook all things are ", shoplist | sooklist) # 합집함
shoping List is  {'k-2', 'walther', 'ppk', 'm16', 'm203'}
sook shoping List is  {'m203', 'ppk', 'k201', 'k-2', 'walther', 'm16'}
the zedo & sook same things are  {'m203', 'k-2', 'walther', 'm16'}
the zedo & sook all things are  {'m203', 'ppk', 'k201', 'k-2', 'walther', 'm16'}

참조(Reference)

리스트(혹은 튜플, 집합) 변수를 할당할때 실제 객체가 변수에 할당되는 것이 아니라 참조가 할당됨 즉 주소값이 복사되어 있는 것임

기본형(정수, 부동소수점, 문자열)은 해당 되지 않음

In [76]:
shoplist=["ppk", "k-2", "walther", "m16", "m203"]
mylist = shoplist
del mylist[0]
print(shoplist)
print(mylist)
['k-2', 'walther', 'm16', 'm203']
['k-2', 'walther', 'm16', 'm203']
In [77]:
# 완전한 복사를 하기 위해서는 슬라이스 연산자(:) 사용 필요함
shoplist=["ppk", "k-2", "walther", "m16", "m203"]
mylist = shoplist[:]
del mylist[0]
print(shoplist)
print(mylist)
['ppk', 'k-2', 'walther', 'm16', 'm203']
['k-2', 'walther', 'm16', 'm203']

문자열 연산 예제

In [79]:
name = 'Swaroop'
if name.startswith('Swa'):
    print('Yes, the string starts with "Swa"')
if 'a' in name:
    print('Yes, it contains the string "a"')
if name.find('war') != -1:
    print('Yes, it contains the string "war"')
delimiter = '_*_'
mylist = ['Brazil', 'Russia', 'India', 'China']
print(delimiter.join(mylist))
Yes, the string starts with "Swa"
Yes, it contains the string "a"
Yes, it contains the string "war"
Brazil_*_Russia_*_India_*_China


'python' 카테고리의 다른 글

Coding the Matrix -3장 Vector(추가)  (0) 2016.05.15
Coding the Matrix-3장 Vector  (0) 2016.05.15
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
TAG more
«   2025/02   »
1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28
글 보관함