🤷 기간 : 2021.04.15 ~ 2021.04.18
🤷 자료 : replit.com
🤷 내용: python
- 함수 만들 때 인수 지정을 안했을 때
def shin():
return a+b
a = 1 # 함수 안의 값 들을 지정해 두면 된당
b = 2
print(shin()) # 3 나옴
- 함수 만들 때 인수 지정 했을 때
def shin(a,b):
return a+b
print(shin(1, 2)) # 3 나옴 / 프린트 할때 해주면 된다
-
def shin():
return a+b
print(shin(1, 2)) # 에러 뜸 / a,b 값을 미리 지정해 둬야된당
print(f"{ } 문자ABC")
>>> name = "shin"
>>> print(f"hello, {name}") # 변수 여러개를 해서 추가할 수도 있다.
hello, shin
>
: 숫자 뿐 아니라 문자(str)에도 사용이 가능하다if character > "b":
print("b 보다 크면 c 혹은 그 다음 알파벳들중 하나 이겠군요?")
if character < "b":
print("b 보다 작으면 a 이겠네요!")
수학 ..^^ 와이리 어렵누 ^^ 잘못 생각하고 있었넹 ㅋㅎ
다음의 방정식을 해결하는 프로그램을 구현 하세요. x값을 구해야 합니다.
ax = b
결과 출력물은 다음과 같아야 합니다.
Hint:
- a 나 b 는 0이 될 수 있습니다.
Examples:
- 만일 a = 1, b = -2 라면 결과값으로 -2가 출력이 되어야 합니다.
- 만일 a = 2, b = -1 라면 결과값으로 "No Solution"이 출력이 되어야 합니다.
제출완료
a = int(input("첫 번째 숫자를 입력해주세요: ")) b = int(input("두 번째 숫자를 입력해주세요: ")) ` if a == 0 and b == 0: # 둘다 0 이면 x값이 암꺼나 나와도 되니까 print("Many Solutions") # 매니솔류션 elif a ==0 and b != 0: # a만 0이면 뭘 넣어도 안되니까 print("No Solution") # 값이 없지 elif a != 0 and b == 0: # b만 0이면 x값은 0만 나올 수 있징? print(0) # 그래서 0 elif a != 0 and b != 0: # 둘다 0이 아닐때 print(b/a) # x값 출력 하고 if b%a != 0: # 나머지 값이 0이 아니면 = 실수(float) 이면 print("No Solution") # 답없당 ~
Positional Parameter
: def love_you(my_name, your_name):
print(f"{my_name} loves {your_name}")
love_you("정우성", "아이유") # 순서에 맞게 값을 넣어 준다.
정우성 loves 아이유
Keyword Arguments
: def love_you(my_name, your_name):
print(f"{my_name} loves {your_name}")
love_you(your_name="아이유", my_name="정우성") # 순서가 아니라 이름에 맞게 넣어줘서 값은 위와 똑같당
정우성 loves 아이유
Mixing positional arguments
and keyword arguments
: keyword arguments
는 순서가 바뀌어도 상관 없지만 / positional arguments
부분은 순서를 지켜줘야 한다는 것입니다. def love_you(my_name, your_name):
print(f"{my_name} loves {your_name}")
love_you(your_name = "아이유", "정우성") # 키워드 아규먼트는 위치 상관 ㄴㄴ, 근데 "정우성"이 my_name쪽에 있으려면 앞으로 가야 겠지? 그래서 이게 안되는거약/ 요건 your_name이 값이 2개가 되는 느낌이지
오류..
def love_you(my_name, your_name):
print(f"{my_name} loves {your_name}")
love_you("정우성", your_name = "아이유")
정우성 loves 아이유
Parameter Default Value
:값이 넘겨지 않은 경우 default 값
이 자동넘어간다default 값이 정의된 parameter
가, default 값이 정의 되지 않은 parameter
보다 먼저 위치해 있으면 안된다 default값
을 주나 ? def love_you(my_name, your_name="아이유"): # 함수에 미리 때려박아 놓는거지 이때 인수 순서가 바뀌면 안되용
print(f"{my_name} loves {your_name}")
love_you("정우성")
정우성 loves 아이유
[Parameter order]
def func
(Regular Positional Arguments
,Default Arguments
,Variable Length Positional Arguments
,Keyword-only Argument
orKeyword-only Argument with default
,Variable Length Keyword Arguments
)- 예제
def func
(a
,b
,c = "shin"
,*args
,a(keyword)
orman=True(keyword)
,kwargs
)
list
와 다른점 ?
그에따른 특이점 ?
for 문
에서 읽어들일때 요소들이 순서대로 나오는게 아니라 무작위 순서대로 나옴.indexing
도 없음>>> set1 = {1, 2, 3, 1}
>>> print(set1)
{1, 2, 3}
>>> set2 = set([1, 2, 3, 1])
>>> print(set2)
{1, 2, 3}
Look up 가능띠
if 문
에서 in
키워드 사용해서 찾아보자 ~ ? my_set = {1, 2, 3}
if 1 in my_set:
print("1 is in the set")
> 1 is in the set
if 4 not in my_set:
print("4 is not in the set")
> 4 is not in the set
set의 사용 함수 ~
add()
: append()
는 리스트에서나 쓰고 여기선 add()
my_set = {1, 2, 3}
my_set.add(4)
print(my_set)
> {1, 2, 3, 4}
remove()
: 사용법은 같아 ~ my_set = {1, 2, 3}
my_set.remove(3)
print(my_set)
> {1, 2}
&
키워드 또는 intersection()
: 교집합 찾을 때set1 = {1, 2, 3, 4, 5, 6}
set2 = {4, 5, 6, 7, 8, 9}
print(set1 & set2)
> {4, 5, 6}
print(set1.intersection(set2))
> {4, 5, 6}
|
키워드 혹은 union()
: 합집합 찾을 때print(set1 | set2)
> {1, 2, 3, 4, 5, 6, 7, 8, 9}
print(set1.union(set2))
> {1, 2, 3, 4, 5, 6, 7, 8, 9}
내부 함수(child function)
는 는 상위 부모 함수(parent function)
안에서만 호출 가능def parent_function():
def child_function():
print("this is a child function")
child_function()
parent_function() # child_function 함수는 parent_function 안에서만 호출이 가능합니다.
> "this is a child function"
함수를 사용하는 이유 ?
중첩 함수를 사용하는 이유 ?
def print_all_elements(list_of_things):
## 중첩함수 선언
def print_each_element(things):
for thing in things:
print(thing)
if len(list_of_things) > 0:
print_each_element(list_of_things)
else:
print("There is nothing!")
Closure는
사전적의미는 폐쇄임..ㅇ
왜 폐쇄하고 격리해서 사용하려는 거야 . ?
중첩함수
는 부모 함수의 변수
나 정보를 가두어서 사용하려고 한다 이것이 closure
중첩 함수
가 부모 함수
의 변수나 정보를 중첩 함수
내에서 사용한다.부모 함수
는 return 값
으로 중첩 함수
를 return
한다.부모함수
의 변수
를 외부로부터 직접적인 접근은 격리하면서도, 중첩 함수
를 통해서 격리된 부모 함수
의 변수
를 사용한 연산은 가능하게 해주는 것입니다.언제 사용하는건데 ?
예
주어진 어떠한 숫자의 수(數) 을 구하는 함수
def calculate_power(number, power):
return number ** power
calculate_power(2, 7)
> 128
2의 승을 구하는 함수 ( 이건 2의 승만 구할 수 있음)
def calculate_power_of_two(power):
return 2 ** power
calculate_power_of_two(7)
> 128
calculate_power_of_two(10)
> 1024
def generate_power(base_number):
def nth_power(power):
return base_number ** power
return nth_power
calculate_power_of_two = generate_power(2)
calculate_power_of_two(7)
> 128
calculate_power_of_two(10)
> 1024
calculate_power_of_seven = generate_power(7)
calculate_power_of_seven(3)
> 343
calculate_power_of_seven(5)
> 16907
이해해봐라 ㅡ ㅡ
사전적의미는 장식 / 뭔가 장식 관련된 걸 껄 ?
왠 파이선에 장식 ? 몬솔이야 ? 할꺼겠지만 한번 알아봅시다.
def jackpot_stock_information():
return "계시가 내려졌습니다. 삼성전자를 사세요!
def is_paid_user():
return True
is_paid_user 함수
가 jackpot_stock_information 함수
보다 먼저 호출 되야 되겠지 당연히 확인 먼저 해야하니까 ? if is_paid_user():
jackpot_stock_information()
Decorator
쓴다 ! ! ! !Decorator
사용법
@
사용 / ()
는 따로 안씀@is_paid_user # 장식(`@`)으로 달린 함수가 먼저 호출이 되고 난 후에 본 함수가 호출
def jackpot_stock_information():
return "계시가 내려졌습니다. 삼성전자를 사세요!"
어떻게 구현하냐 ? 암꺼다 다돼 ?
Decorator
로 장식할 수 있는 함수는 중첩 함수(nested function)
을 return
하는 함수만 decorator
함수로 사용즉 , decorator
= chain of functions
decorator
함수는 그 다음 함수를 리턴해줘야함is_paid_user 함수
를 decorator
로 만들어 볼까요 ? ?def is_paid_user(func):
user_paid = True # 간단화 하기 위해 무조건 True
def wrapper(*args, **kwargs):
if user_paid:
func()
else:
return
return wrapper # 중첩함수"is_paid_user(func)"는 다음 함수인 "wrapper( )"를 리턴하지요 ?
-> 방금 만든 is_paid_user 함수
를 decorator
인 @
해주면 끝
@is_paid_user
def jackpot_stock_information():
return "계시가 내려졌습니다. 삼성전자를 사세요!"
실 사용법
decorator 사용
def trace(func): # 호출할 함수를 매개변수로 받음 def wrapper(): print(func.__name__, '함수 시작') # __name__으로 함수 이름 출력 func() # 매개변수로 받은 함수를 호출 print(func.__name__, '함수 끝') return wrapper # wrapper 함수 반환 ` @trace # @데코레이터 def hello(): print('hello') ` @trace # @데코레이터 def world(): print('world') ` hello() # 함수를 그대로 호출 world() # 함수를 그대로 호출
hello 함수 시작 hello hello 함수 끝 world 함수 시작 world world 함수 끝
decorator 사용 안한거
decorator_closure.py def trace(func): # 호출할 함수를 매개변수로 받음 def wrapper(): # 호출할 함수를 감싸는 함수 print(func.__name__, '함수 시작') # __name__으로 함수 이름 출력 func() # 매개변수로 받은 함수를 호출 print(func.__name__, '함수 끝') return wrapper # wrapper 함수 반환 ` def hello(): print('hello') ` def world(): print('world') ` trace_hello = trace(hello) # 데코레이터에 호출할 함수를 넣음 trace_hello() # 반환된 함수를 호출 trace_world = trace(world) # 데코레이터에 호출할 함수를 넣음 trace_world() # 반환된 함수를 호출
hello 함수 시작 hello hello 함수 끝 world 함수 시작 world world 함수 끝
decorator 2개 사용
def decorator1(func): def wrapper(): print('decorator1') func() return wrapper ` def decorator2(func): def wrapper(): print('decorator2') func() return wrapper ` # 데코레이터를 여러 개 지정 @decorator1 @decorator2 def hello(): print('hello') ` hello()
decorator1 decorator2 hello
replit 53번 문제 답
def welcome_decorator(func): def wrapper(): a = "welcome to WECODE!" b = func() return (b+a) # 위는 그냥 해도 됬었는데 이건 ;; 뭐지 근데 리턴값이 나와야하니까 여기 꼭 리턴값은 써주자 return wrapper ` @welcome_decorator def greeting(): return "Hello, " ` greeting()
프로그래밍 언어에서 scope은 어떠한 객체 (변수, 함수 등)가 유효한 범위를 이야기 하며, 범위를 벗어나면 해당 객체는 사용될 수 없습니다.
Python에서 scope은 항상 객체가 선언된 지점에서 위로는 상위 객체 까지, 아래로는 모든 하위 객체들과 그 안에까지가 범위 입니다.
나
함수혹은
객체`는 *특정(local) 범위**에서만 유효함수
안에 들어가 있는 변수
나 함수
는 그 함수 안에서만 유효한다.중첩함수가 있을때 적용되는 Scope
위의 방법을 ìdle
출력하면 1
,7
,none
이렇게 나옴
아래로 하면 값만 딱 얻을 수 있당 ~ 참고해
def outer():
a=5
def inner():
b=7
return a * b
return inner
`
test = outer()
print(test())
35
변수
나 함수
변수
와 함수
들이 해당 파일에서 가장 바깥쪽에서 선언되므로 해당 파일에서 선언된 지점 아래로는 다 유효한 범위를 가지고 있습니다len()
def shadowing()