티스토리 뷰


Function

선언 및 사용

함수를 정의할 때는 

def function(parameter):

형식으로 사용한다.

def printTest():
print('test')

printTest()


파라미터가 있을경우는 아래와 같이 처리한다.

def changeToWon(dollar):
print(dollar * 1147.50)

changeToWon(1)


python 은 return 형을 지정해줄 필요가 없다.

def changeToWon(dollar):
won = dollar * 1147.50
print(won)
return won

won = changeToWon(1)


parameter 를 전달하지 않았을 때 

default Value 도 지정해줄 수 있다.


def changeToWon(dollar, currency=1147.50):
won = dollar * currency
print(won)
return won

won = changeToWon(1)
won = changeToWon(1, 1148)



변수 범위 (Variable Scope)

number = 1234  # 전역변수

def test():
number = 222 # 지역변수
print(number)

test() # 222
print(number) # 1234



Keywork Argument

def silly_sentence(name='Lucy', action='ate', item='jelly'):
print(name, action, item)

silly_sentence() # -> Lucy ate jelly
silly_sentence('Harry', 'play', 'games') # -> Harry play games
silly_sentence(item='hamburger') # -> Lucy ate hamburger
silly_sentence(name='Kelly', action='play with', item='Chris') # -> Kelly play with Chris



Flexible number of Argument

전달받을 parameter 가 몇개일지 모를 때,

임의의 개수를 지정하게 할 수 있다.

Asterisk sign (*) 을 붙여주면 몇개인지 모르겠지만

여러개의 인자가 들어올 것이라는 것을 지정할 수 있다.


def add_numbers(*numbers):
total = 0
for i in numbers:
total += i
print(total)

add_numbers(1, 2, 3, 4, 5, 6, 7)


Unpacking Argument

def add_numbers(first, second, third):
total = first + second + third
print(total)

numbers = [1, 2, 3]
add_numbers(numbers[0], numbers[1], numbers[2])
add_numbers(*numbers)

위 경우와 Flexible Number of argument 는 함께 사용할 수도 있다.

def add_numbers(*numbers):
total = 0
for i in numbers:
total += i
print(total)

numbers = [1, 2, 3, 4, 5, 6, 7]
add_numbers(*numbers) # -> add_numbers(1, 2, 3, 4, 5, 6, 7)



Collections

Lists

name = ['kim', 'lee', 'park', 'choi', 'ryu', 'cho', 'kang']

name.insert(3, 'lim') # -> 3번째 index 에 'lim' 추가
name += ['jung'] # -> append 와 동일, - 는 존재하지 않음

name.index('park') # -> name list 에서 'park' index, 없으면 ValueError 발생
name.index('park', 2) # -> 2번째 index 부터 'park' index 찾음
name.pop() # -> 맨 끝 index 삭제
name.pop(4) # -> 4번째 index 값을 지운다.
name.remove('kang') # -> 'kang' 을 지운다.

name.sort() # -> ASC 기준 정렬
name.reverse() #-> DESC 기준 정렬

def lastSorting(x):
return x[-1] #맨 끝 글자를 이용해 정렬함
name.sort(key=lastSorting)


Sets

중복을 걸러내주는 집합 역할을 한다.
shopping_list = {'stapler', 'milk', 'egg', 'egg', 'beer', 'beer'}
print(shopping_list) # -> {'milk', 'beer', 'egg', 'stapler'}


shopping_list = {'stapler', 'milk', 'egg', 'egg', 'beer', 'beer'}
inputItem = input("Which one do you need?")
if inputItem in shopping_list:
print("You already have in the list")
else:
print("You need to put it")

중복 제거 속성을 이용해서 사용자에게 Input 을 받아

Set 안에 있는지 확인하는 로직이다.


[console]

Which one do you need?coffee

You need to put it



Set 에는 여러가지 함수가 존재한다. 

builtins.py 안 set 클래스에서 확인할 수 있다.


num1 = {1, 2, 3}
num2 = {3, 4, 5}

union_set = num1.union(num2) # -> {1, 2, 3, 4, 5}, = num1 | num2, 합집합
inter_set = num1.intersection(num2) # -> {3}, = num1 & num2, 교집합
num1 - num2 # -> {1, 2}, 차집합

num1.add(8)
num1.remove(1) # 만약, set 에 값이 존재하지 않으면 KeyError 발생
num1.clear()
issubset = num1.issubset(num2)
iscontain = num2.__contains__(4)


Dictionary

friends = {'Tony': 'chubby', 'Lucy': 'pretty', 'Eric': 'smart'}

print(friends) # -> {'Tony': 'chubby', 'Lucy': 'pretty', 'Eric': 'smart'}
print(friends['Tony']) # -> chubby
print(friends['Eric']) # -> smart

for k, v in friends.items():
print(k + '\'s ' + v) # -> Tony's chubby, Lucy's pretty, Eric's smart

for v in friends.values():
print(v) # -> smart, pretty, chubby



Tuple

읽기 전용으로 사용된다.

(, ) 로 묶어서 정의한다.

속도가 빠르지만 제공하는 함수가 적다.


ntuple = (6, 7, 8)

nset = set(ntuple)
print(nset) # ->{8, 6, 7}

nlist = list(ntuple)
print(nlist) # ->[6, 7, 8]



출처 

http://creativeworks.tistory.com/m/category/Programming/Python%20Tutorials 의 11~19, 35 장

http://devcosin.tistory.com/5


공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/05   »
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 29 30 31
글 보관함