Programing

Python은 단락을 지원하는가?

c10106 2022. 3. 17. 21:15
반응형

Python은 단락을 지원하는가?

Python은 부울식에서의 단락을 지원하는가?

네, 둘 다요and그리고or연산자 단락 - 문서를 참조하십시오.

운영자 내 단락 동작and,or:

먼저 어떤 것이 실행되었는지 아닌지를 판단할 수 있는 유용한 기능을 정의해 보자.인수를 수락하고 메시지를 인쇄한 후 입력 내용을 변경하지 않고 반환하는 간단한 기능.

>>> def fun(i):
...     print "executed"
...     return i
... 

파이썬의 단락 행동을 관찰할 수 있다.and,or다음 예제의 연산자:

>>> fun(1)
executed
1
>>> 1 or fun(1)    # due to short-circuiting  "executed" not printed
1
>>> 1 and fun(1)   # fun(1) called and "executed" printed 
executed
1
>>> 0 and fun(1)   # due to short-circuiting  "executed" not printed 
0

참고: 통역자는 다음 값을 거짓으로 간주한다.

        False    None    0    ""    ()    []     {}

기능상 단락 동작:any(),all():

파이썬과 기능도 단락을 지원한다.문서에 나타난 바와 같이, 그들은 평가에서 조기 종료를 허용하는 결과를 찾을 때까지 순서의 각 요소를 순서대로 평가한다.아래 예제를 참고하여 두 가지를 모두 이해하십시오.

함수는 요소가 참인지 여부를 점검한다.True가 발견되는 즉시 실행을 중지하고 True를 반환한다.

>>> any(fun(i) for i in [1, 2, 3, 4])   # bool(1) = True
executed
True
>>> any(fun(i) for i in [0, 2, 3, 4])   
executed                               # bool(0) = False
executed                               # bool(2) = True
True
>>> any(fun(i) for i in [0, 0, 3, 4])
executed
executed
executed
True

함수는 모든 요소가 True인지 확인하고 False가 발생하는 즉시 실행을 중지한다.

>>> all(fun(i) for i in [0, 0, 3, 4])
executed
False
>>> all(fun(i) for i in [1, 0, 3, 4])
executed
executed
False

체인 비교의 단락 동작:

추가로 파이썬에서

비교는 임의로 사슬로 묶을있다. 예를 들어,x < y <= z와 같다x < y and y <= z, 그것을 제외하고.y한 번만 평가됨(그러나 두 경우 모두)z다음에 대해 전혀 평가되지 않음x < y거짓으로 판명되다.

>>> 5 > 6 > fun(3)    # same as:  5 > 6 and 6 > fun(3)
False                 # 5 > 6 is False so fun() not called and "executed" NOT printed
>>> 5 < 6 > fun(3)    # 5 < 6 is True 
executed              # fun(3) called and "executed" printed
True
>>> 4 <= 6 > fun(7)   # 4 <= 6 is True  
executed              # fun(3) called and "executed" printed
False
>>> 5 < fun(6) < 3    # only prints "executed" once
executed
False
>>> 5 < fun(6) and fun(6) < 3 # prints "executed" twice, because the second part executes it again
executed
executed
False

편집:
한 가지 더 흥미로운 점:- Python의 논리 , 연산자는 부울 대신 피연산자의 을 반환한다.True또는False예:

작전x and y결과를 주다if x is false, then x, else y

다른 언어와 달리(예:&&,||0 또는 1을 반환하는 C의 연산자.

예:

>>> 3 and 5    # Second operand evaluated and returned 
5                   
>>> 3  and ()
()
>>> () and 5   # Second operand NOT evaluated as first operand () is  false
()             # so first operand returned 

유사하게or연산자가 다음 값 중 가장 많은 값을 반환함bool(value)==True기타 대부분의 거짓 값(단락 동작에 따라)을 바로잡는다. 예:

>>> 2 or 5    # left most operand bool(2) == True
2    
>>> 0 or 5    # bool(0) == False and bool(5) == True
5
>>> 0 or ()
()

그렇다면, 이것은 어떻게 유용할까?한 예가 실용 파이썬 바이 매그너스 리 헤틀란드에 제시되어 있다.
사용자가 이름을 입력해야 하지만 아무 것도 입력하지 않을 수 있으며, 이 경우 기본값을 사용하려는 경우'<Unknown>'. if 문구를 사용할 수도 있지만 매우 간명하게 다음과 같이 말할 수도 있다.

In [171]: name = raw_input('Enter Name: ') or '<Unknown>'
Enter Name: 

In [172]: name
Out[172]: '<Unknown>'

즉, 반환 값이 다음 값인 경우raw_inputtrue임(빈 문자열 아님), 이름에 할당됨(변경되지 않음), 그렇지 않으면 기본값'<Unknown>'에 할당되다name.

예. 파이선 통역기에서 다음을 시도해 보십시오.

그리고

>>>False and 3/0
False
>>>True and 3/0
ZeroDivisionError: integer division or modulo by zero

또는

>>>True or 3/0
True
>>>False or 3/0
ZeroDivisionError: integer division or modulo by zero

그렇다, 파이톤은 부울 연산자에 대한 단락 평가, 최소 평가 또는 매카시 평가를 지원한다.부울식 출력을 계산하기 위한 평가 횟수를 줄이기 위해 사용된다.예제 -

기본 함수

def a(x):
    print('a')
    return x

def b(x):
    print('b')
    return x 

AND

if(a(True) and b(True)):
    print(1,end='\n\n')

if(a(False) and b(True)):
    print(2,end='\n\n') 

And-Output

a
b
1

a 

OR

if(a(True) or b(False)):
    print(3,end='\n\n')

if(a(False) or b(True)):
    print(4,end='\n\n') 

OR-Output

a
3

a
b
4 

참조URL: https://stackoverflow.com/questions/2580136/does-python-support-short-circuiting

반응형