43_재귀함수 + 팩토리얼
-재귀함수 : 자기자신을 연산하는 것
inputN = int(input('input number : '))
resultSum = 1
def factorialN(n):
for i in range(1, (n + 1)):
global resultSum
resultSum *= i
print(resultSum)
factorialN(inputN)
[Output]
#UnboundLocalError: local variable 'resultSum' referenced before assignment 이런 에러가 뜬다.
# 원인 : for, while, if 안에서 선언된 변수를 밖에서 쓰려고 할 때 문제, 두 변수가 연결되어 있지 않기 때문이다 이를 variable shadowing이라고 한다.
-> 변수를 global로 처리
In computer programming, variable shadowing occurs when a variable declared within a certain scope (decision block, method, or inner class) has the same name as a variable declared in an outer scope. At the level of identifiers (names, rather than variables), this is known as name masking. This outer variable is said to be shadowed by the inner variable, while the inner identifier is said to mask the outer identifier. This can lead to confusion, as it may be unclear which variable subsequent uses of the shadowed variable name refer to, which depends on the name resolution rules of the language.
-> 바깥 범위에 있는 변수와 같은 이름의 변수가 특정 범위 안에 있을 때 발생하는 현상.
.
.
inputN = int(input('input number : '))
resultSum = 1
def factorialN(n):
resultSum = 1
for i in range(1, (n + 1)):
resultSum *= i
print(resultSum)
factorialN(inputN)
.
.
def recursionFun(n):
if n == 1:
return n
return n * recursionFun(n-1) #자기자신을 연산하는 것을 재귀함수라고 함
inputN = int(input('input number : '))
print(format(recursionFun(inputN), ','))