파이썬 스터디6

seonae's wiki
이동: 둘러보기, 검색

스터디 홈


파일

  • 파일 생성하기
f = open("sample.txt", 'w')  # r, w, a
f.close()
  • 파일 쓰기
f = open("sample.txt", 'w')
for i in range(1, 11):
    data = "%d번째 줄입니다.\n" % i
    f.write(data)
f.close()
  • 파일 추가
f = open("sample.txt", 'a')
for i in range(11, 20):
    data = "%d번째 줄입니다.\n" % i
    f.write(data)
f.close()
  • 파일함수
#readline()
f = open("sample.txt", 'r')
while True:
    line = f.readline()
    if not line: break
    print(line)
f.close()

#readlines()
f = open("sample.txt", 'r')
lines = f.readlines()
for line in lines:
    print(line)
f.close()

#read()
f = open("sample.txt", 'r')
data = f.read()
print(data)
f.close()
  • with문
with open("foo.txt", "w") as f:
    f.write("Life is too short, you need python")

점프투 파이썬 연습문제

함수

  • 함수의 구조
def 함수명(매개변수):
    <수행할 문장1>
    <수행할 문장2>
    ...

def add(a, b): 
    return a + b
  • 예시
#일반
def 함수이름(매개변수):
    <수행할 문장>
    ...
    return 결과값

#parameter 없음
>>> def say(): 
...     return 'Hi' 
>>> a = say()
>>> print(a)

#return 없음
>>> def add(a, b): 
...     print("%d, %d의 합은 %d입니다." % (a, b, a+b))
>>> add(3, 4)

>>> a = add(3, 4)
>>> print(a)

#no parameter, no return
>>> def say(): 
...     print('Hi')
>>> say() # 함수명() 실행
  • lambda 한줄함수
lambda 매개변수1, 매개변수2, ... : 매개변수를 이용한 표현식

>>> add = lambda a, b: a+b
>>> result = add(3, 4)
>>> print(result)

점프투 파이썬 연습문제