함수 사용법(들여쓰기로 함수 판단)
print 함수
파라미터 값이 없는 경우
def say_hello():
print("hello")
say_hello() # hello
파라미터 값이 있는 경우
def say_hello(who):
print("hello", who)
say_hello("Awos") # hello Awos
def plus(a, b):
print(a + b)
plus(2, 5) # 7
def minus(a, b):
print(a - b)
minus(2, 5) # -3
파라미터 값이 있고 default 값이 있는 경우
def say_hello(name="anonymous"):
print("hello", name)
say_hello() # hello anonymous
say_hello("awos") # hello awos
일반적인 함수
return 을 쓰게 되면 함수를 호출할 때 함수가 return 된 값으로 치환됨
r_result는 return 된 값인 5가 나오는 것이고
p_result는 콘솔 창에 그냥 print 한 것, 그래서 None 값이 뜬다.
def p_plus(a, b):
print(a + b)
def r_plus(a, b):
return a + b
p_result = p_plus(2, 3)
r_result = r_plus(2, 3)
print(p_result, r_result) # None 5
파라미터 값을 넣어 String으로 return하는 함수
String formatting
사용법 return f"~~~~~~~"
def say_hello(name, age):
return f"Hello {name} you are {age} years old"
hello = say_hello("awos", "12")
print(hello) # Hello awos you are 12 years old
위의 코드와 같은 방법 '+'로 문자열 연결 (하지만 비추)
def say_hello(name, age):
return "Hello " + name + " you are " + age +" years old"
hello = say_hello("awos", "12")
print(hello) # Hello awos you are 12 years old
keyword argument : 인자의 개수가 1,2개면 괜찮은데 여러개일 경우
아래의 코드와 같이 인자값 바로앞에 keyword를 붙여서 이게 어디에 쓰이는 값인지 알 수 있다
또 keyword를 붙여주면 인자의 순서에 상관없이 keyword가 있기 때문에 오류를 발생시키지 않을 수 있다
hello = say_hello(name="awos", age="12")