3.1. 함수

- 돌려받을 값이 없는 함수를 변수에 대입하면 None 이 출력된다.

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

 

- 매개변수 지정하여 호출하기: add(a=3, b=7)

 

- 미지수의 여러 입력값: def add_many(*args):

- 키워드 파라미터: def print_kwargs(**kwargs):

def print_kwargs(**kwargs):
	print(kwargs)
    
print_kwargs(a=1)
{'a': 1}

 

- 튜플값으로 return 하기

def add_and_mul(a,b):
	return a+b, a*b
    
result = add_and_mul(3, 4)
result1, result2 = add_and_mul(5, 6)

 

- 매개변수 초기값 설정하기: def say_myself(name, age, sex="F"):

def say_myself(name, age, sex="F"):
    print("My name is %s" % name)
    print("My age is %d" % age)
    if sex == "F":
        print("Female")
    elif sex == "M":
        print("Male")
    else:
        raise Exception("There not exist %s" % sex)

say_myself("배수지", 31)
say_myself("홍길동", 30, "M")

* 초기값 설정해 놓은 매개변수는 초기값 설정하지 않은 매개변수 뒤에 선언해야 한다.

* args, kwargs 는 관례적 이름이다.

 

- 함수 안 선언 변수의 효력 범위는 자바와 마찬가지로 함수 안에서만 사용될 뿐 바깥의 변수랑은 상관이 없다.

- global 명령어: 함수 밖 변수를 사용할 수 있게 해준다. 독립성을 위해 가급적 사용하지 않는게 좋다.

 

- lambda: 함수를 한줄로 간결하게 만들 때 사용한다.

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

 

3.2. 사용자 입력과 출력

- input 함수: input(), input("숫자를 입력하세요: ")

 

- print 문: 큰따옴표(")로 둘러쌓인 문자열은 '+', 콤마(,) 는 '뛰어쓰기'

매개변수 end를 사용해 끝 문자를 지정할 수 있다.

>>> print("life" "is" "too short")
lifeistoo short
>>> print("life", "is", "too short")
life is too short
>>> for i in range(10):
	print(i, end=' ')

 

3.3. 파일 읽고 쓰기

- 파일 생성: open

f = open("새파일.txt", 'w') # 파일 열기 모드로 'r', 'w', 'a', 순서대로 읽기, 쓰기, 추가 모드를 사용할 수 있다.
f.close() # 파일 모드를 바꾸기 전에 close를 해야 제대로 작동한다.

현재 경로를 확인하기 위해 아래의 코드를 사용할 수 있다.

import os
path = os.getcwd()
print(path)

 

- 파일 쓰기: f.write("%d 번째 줄입니다.\n" % i)

- 파일 읽기: f.readline(), f.readlines(), f.read()

def readline():
    while True:
        line = f.readline()
        if not line:
   		    break
        print(line.strip()) # 줄바꿈(\n) 문자 제거
    
def readlines():
    lines = f.readlines()
    for line in lines:
    	print(line.strip())
 
def read():
    data = f.read()
    print(data)

path = "/Users/user/vsc-workspace/python/_4_io/_4_2_file_io/새파일.txt"
f = open(path, 'r')
readline()
readlines()
read()
f.close()

- 왼쪽부터 순서대로 한줄 읽기, 줄을 리스트 요소로 가져오기, 내용 전체 돌려주기 이다.

- with문과 함께 사용하기: with 블록을 벗어난 순간 열린 파일 객체 f 가 자동으로 close 된다.

with open("foo.txt", 'w') as f:
	f.write("Life is too short, you need python")

 

- sys 모듈로 매개변수 주기

import sys
args = sys.argv[1:]
for i in args:
	print(i)

'''
python3 sys1.py aaa bbb ccc
를 실행하면 argv[0] 인 sys1.py 이후부터 출력한다.
'''

 

블로그 이미지

uchacha

개발자 일지

,