python
def greet():
print("Hello, Python!")
python
greet()
python
def add(a, b):
return a + b
result = add(3, 5)
print(result)
Python 함수는 다양한 방식으로 인자(argument)를 받을 수 있습니다.
python
def info(name, age):
print(f"{name}은 {age}살입니다.")
info("Alice", 30)
python
def greet(name="python"):
print(f"Hello, {name}!")
greet() #Hello, Python!
greet("Alice") #Hello, Alice!
python
def student(name, grade):
print(f"{name}의 성적은 {grade}입니다.")
student(grade="A+", name="Bob")
python
def total(*numbers):
print(numbers)
print(sum(numbers))
total(1,2,3,4)
python
def print_info(**kwargs):
for key, value in kwargs.items():
print(f"{key} : {value}")
print_info(name="Alice", age=25)
python
square = lambda X: X ** 2
print(square(4)) # 16
python
nums = [1, 2, 3, 4]
squares = list(map(lambda x: x ** 2, nums))
print(squares) #[1, 3, 9, 16]
python
def factorial(n):
if n == 1:
return 1
return n * factorial(n - 1)
print(factorial(5))
python
def example():
x = 10
print(x)
example()
python
x = 100
def show():
print(x)
show()
python
def outer():
x = "outer"
def inner():
nonlocal x
x = "inner"
요약정리
| 구분 | 설명 |
| ----------- | -------------------- |
| def | 함수 정의 키워드 |
| return | 함수의 결과값 반환 |
| *args | 가변 위치 인자 (튜플로 전달) |
| **kwargs | 가변 키워드 인자 (딕셔너리로 전달) |
| lambda | 익명 함수 |
| global | 전역 변수 수정 |
| nonlocal | 바깥 함수의 지역 변수 수정 |
| recursion | 함수가 자기 자신을 호출 |
이번 편에서는 Python의 함수 정의 및 호출, 인자 처리 방식, 익명 함수와 재귀, 그리고 스코프의 개념까지 함수에 대한 핵심적인 내용을 정리했습니다.
다음 편에서는 Python의 예외처리에 대해 공부해보겠습니다.