return 문의 목적은 무엇입니까?
return 문이 무엇인지, 파이썬에서 사용하는 방법에 대한 간단한 기본 설명은 무엇입니까?
그리고 그것과 print진술 의 차이점은 무엇 입니까?
이 print()함수는 콘솔에 문자열을 씁니다. 즉, "prints"입니다. 이 return명령문은 함수를 종료하고 호출자에게 값을 돌려 주도록합니다. 일반적으로 함수의 요점은 입력을 받아 무언가를 반환하는 것입니다. 이 return명령문은 함수가 호출자에게 값을 반환 할 준비가되었을 때 사용됩니다.
예를 들어 다음은 print()및 모두를 활용하는 함수입니다 return.
def foo():
print("hello from inside of foo")
return 1
이제 다음과 같이 foo를 호출하는 코드를 실행할 수 있습니다.
if __name__ == '__main__':
print("going to call foo")
x = foo()
print("called foo")
print("foo returned " + str(x))
.pyPython 인터프리터와 달리 스크립트 (예 : 파일)로 실행 하면 다음과 같은 출력이 표시됩니다.
going to call foo
hello from inside foo
called foo
foo returned 1
이것이 더 명확 해지기를 바랍니다. 인터프리터는 반환 값을 콘솔에 기록하므로 누군가가 왜 혼란 스러울 수 있는지 알 수 있습니다.
다음은이를 보여주는 인터프리터의 또 다른 예입니다.
>>> def foo():
... print("hello from within foo")
... return 1
...
>>> foo()
hello from within foo
1
>>> def bar():
... return 10 * foo()
...
>>> bar()
hello from within foo
10
foo()에서 호출 bar()되면 1이 콘솔에 기록되지 않음을 알 수 있습니다 . 대신에서 반환 된 값을 계산하는 데 사용됩니다 bar().
print()부작용 (콘솔에 문자열 쓰기)을 유발하는 함수이지만 실행은 다음 문으로 다시 시작됩니다. return함수가 실행을 중지하고 호출 된 값을 반환합니다.
여기서는 사전 이 최고의 참고 자료 라고 생각합니다
요컨대 :
return 은 무언가를 돌려 주거나 print 가 텍스트를 생성 하는 동안 함수 호출자에게 응답 합니다.
print 문을 부작용 을 일으키는 것으로 생각하면 함수가 사용자에게 텍스트를 작성하지만 다른 함수에서는 사용할 수 없습니다 .
몇 가지 예와 Wikipedia의 몇 가지 정의를 통해이를 더 잘 설명 할 것입니다.
다음은 Wikipedia의 함수 정의입니다.
수학에서 함수는 입력이라고도하는 함수의 인수 인 한 수량을 출력이라고도하는 함수의 값인 다른 수량과 연관시킵니다.
잠시 생각해보십시오. 함수에 값이 있다는 것은 무엇을 의미합니까?
의미하는 바는 실제로 함수의 값을 일반 값으로 대체 할 수 있다는 것입니다! (두 값이 동일한 유형의 값이라고 가정)
왜 물어보고 싶습니까?
무엇으로 값이 동일한 유형의 동의를 할 수있는 다른 기능에 대한 입력을 ?
def square(n):
return n * n
def add_one(n):
return n + 1
print square(12)
# square(12) is the same as writing 144
print add_one(square(12))
print add_one(144)
#These both have the same output
출력을 생성하기 위해 입력에만 의존하는 함수에 대한 멋진 수학적 용어가 있습니다. 참조 투명성. 다시, Wikipedia의 정의.
참조 투명성과 참조 불투명도는 컴퓨터 프로그램의 일부 속성입니다. 프로그램의 동작을 변경하지 않고 값으로 바꿀 수있는 표현식은 참조 적으로 투명하다고합니다.
프로그래밍이 처음이라면 이것이 무엇을 의미하는지 이해하기가 조금 어려울 수 있지만 몇 가지 실험 후에 얻을 수있을 것입니다. 그러나 일반적으로 함수에서 인쇄와 같은 작업을 수행 할 수 있으며 끝에 return 문을 사용할 수도 있습니다.
return을 사용할 때 기본적으로 "이 함수에 대한 호출은 반환되는 값을 쓰는 것과 동일합니다."라는 것을 기억하십시오.
파이썬은 여러분이 직접 입력하는 것을 거부하면 실제로 반환 값을 삽입합니다. 이것은 "None"이라고 불리며 단순히 아무것도 의미하지 않거나 null을 의미하는 특별한 유형입니다.
파이썬에서는 "def"로 함수 정의를 시작하고 일반적으로 "return"으로 함수를 종료합니다.
변수 x의 함수는 f (x)로 표시됩니다. 이 기능은 무엇을합니까? 이 함수가 x에 2를 더한다고 가정합니다. 그래서 f (x) = x + 2
이제이 함수의 코드는 다음과 같습니다.
def A_function (x):
return x + 2
함수를 정의한 후이를 모든 변수에 사용하고 결과를 얻을 수 있습니다. 예 :
print A_function (2)
>>> 4
다음과 같이 코드를 약간 다르게 작성할 수 있습니다.
def A_function (x):
y = x + 2
return y
print A_function (2)
그것은 또한 "4"를 줄 것입니다.
이제이 코드를 사용할 수도 있습니다.
def A_function (x):
x = x + 2
return x
print A_function (2)
이것은 또한 4를 줄 것입니다. 반환 옆의 "x"는 실제로 "A_function (x)"의 x가 아니라 (x + 2)를 의미합니다.
이 간단한 예를 통해 return 명령의 의미를 이해할 수있을 것 같습니다.
이 답변은 위에서 논의되지 않은 일부 경우에 대해 설명합니다. 반환 문을 사용하면 할 수 있습니다 종료 당신이 끝에 도달하기 전에 함수의 실행을. 이로 인해 실행 흐름이 즉시 호출자에게 반환됩니다.
4 번 줄 :
def ret(n):
if n > 9:
temp = "two digits"
return temp #Line 4
else:
temp = "one digit"
return temp #Line 8
print("return statement")
ret(10)
조건문이 실행 된 후 ret()함수는 return temp(4 행) 으로 인해 종료됩니다 . 따라서 print("return statement")실행되지 않습니다.
산출:
two digits
조건문 뒤에 나타나는이 코드 또는 제어 흐름이 도달 할 수없는 위치는 데드 코드 입니다.
값 반환
4 번과 8 번 줄에서 return 문은 조건이 실행 된 후 임시 변수의 값을 반환하는 데 사용됩니다.
인쇄 와 반환 의 차이를 드러내려면 :
def ret(n):
if n > 9:
print("two digits")
return "two digits"
else :
print("one digit")
return "one digit"
ret(25)
산출:
two digits
'two digits'
return "이 함수에서이 값을 출력"을 의미합니다.
print "이 값을 (일반적으로) stdout으로 전송"을 의미합니다.
Python REPL에서 함수 반환은 기본적으로 화면에 출력됩니다 (인쇄와 완전히 동일하지 않음).
다음은 인쇄의 예입니다.
>>> n = "foo\nbar" #just assigning a variable. No output
>>> n #the value is output, but it is in a "raw form"
'foo\nbar'
>>> print n #the \n is now a newline
foo
bar
>>>
다음은 반환의 예입니다.
>>> def getN():
... return "foo\nbar"
...
>>> getN() #When this isn't assigned to something, it is just output
'foo\nbar'
>>> n = getN() # assigning a variable to the return value. No output
>>> n #the value is output, but it is in a "raw form"
'foo\nbar'
>>> print n #the \n is now a newline
foo
bar
>>>
@Nathan Hughes의 탁월한 답변에 추가하기 만하면됩니다.
return문은 제어 흐름의 일종으로 사용할 수 있습니다. return함수 중간에 하나 (또는 그 이상의) 명령문 을 넣으면 "이 함수 실행을 중지합니다. 원하는 것을 얻었거나 뭔가 잘못되었습니다!"라고 말할 수 있습니다.
예를 들면 다음과 같습니다.
>>> def make_3_characters_long(some_string):
... if len(some_string) == 3:
... return False
... if str(some_string) != some_string:
... return "Not a string!"
... if len(some_string) < 3:
... return ''.join(some_string,'x')[:,3]
... return some_string[:,3]
...
>>> threechars = make_3_characters_long('xyz')
>>> if threechars:
... print threechars
... else:
... print "threechars is already 3 characters long!"
...
threechars is already 3 characters long!
이러한 .NET 사용 방법에 대한 자세한 내용은 Python 가이드 의 코드 스타일 섹션 을 참조하세요 return.
"반품"과 "인쇄"의 차이점은 다음 예에서도 확인할 수 있습니다.
반환:
def bigger(a, b):
if a > b:
return a
elif a <b:
return b
else:
return a
위의 코드는 모든 입력에 대해 올바른 결과를 제공합니다.
인쇄:
def bigger(a, b):
if a > b:
print a
elif a <b:
print b
else:
print a
참고 : 이는 많은 테스트 사례에서 실패합니다.
오류:
----
FAILURE: Test case input: 3, 8.
Expected result: 8
FAILURE: Test case input: 4, 3.
Expected result: 4
FAILURE: Test case input: 3, 3.
Expected result: 3
You passed 0 out of 3 test cases
여기 내 이해가 있습니다. (누군가를 도울 것이며 정확하기를 바랍니다.)
def count_number_of(x):
count = 0
for item in x:
if item == "what_you_look_for":
count = count + 1
return count
So this simple piece of code counts number of occurrences of something. The placement of return is significant. It tells your program where do you need the value. So when you print, you send output to the screen. When you return you tell the value to go somewhere. In this case you can see that count = 0 is indented with return - we want the value (count + 1) to replace 0. If you try to follow logic of the code when you indent the return command further the output will always be 1, because we would never tell the initial count to change. I hope I got it right. Oh, and return is always inside a function.
return is part of a function definition, while print outputs text to the standard output (usually the console).
A function is a procedure accepting parameters and returning a value. return is for the latter, while the former is done with def.
Example:
def timestwo(x):
return x*2
return should be used for recursive functions/methods or you want to use the returned value for later applications in your algorithm.
print should be used when you want to display a meaningful and desired output to the user and you don't want to clutter the screen with intermediate results that the user is not interested in, although they are helpful for debugging your code.
The following code shows how to use return and print properly:
def fact(x):
if x < 2:
return 1
return x * fact(x - 1)
print(fact(5))
This explanation is true for all of the programming languages not just python.
Best thing about return function is you can return a value from function but you can do same with print so whats the difference ? Basically return not about just returning it gives output in object form so that we can save that return value from function to any variable but we can't do with print because its same like stdout/cout in C Programming.
Follow below code for better understanding
CODE
def add(a, b):
print "ADDING %d + %d" % (a, b)
return a + b
def subtract(a, b):
print "SUBTRACTING %d - %d" % (a, b)
return a - b
def multiply(a, b):
print "MULTIPLYING %d * %d" % (a, b)
return a * b
def divide(a, b):
print "DIVIDING %d / %d" % (a, b)
return a / b
print "Let's do some math with just functions!"
age = add(30, 5)
height = subtract(78, 4)
weight = multiply(90, 2)
iq = divide(100, 2)
print "Age: %d, Height: %d, Weight: %d, IQ: %d" % (age, height, weight, iq)
# A puzzle for the extra credit, type it in anyway.
print "Here is a puzzle."
what = add(age, subtract(height, multiply(weight, divide(iq, 2))))
print "That becomes: ", what, "Can you do it by hand?"
We are now doing our own math functions for add, subtract, multiply, and divide. The important thing to notice is the last line where we say return a + b (in add). What this does is the following:
- Our function is called with two arguments:
aandb. - We print out what our function is doing, in this case "ADDING."
- Then we tell Python to do something kind of backward: we return the addition of
a + b. You might say this as, "I addaandbthen return them." - Python adds the two numbers. Then when the function ends, any line that runs it will be able to assign this
a + bresult to a variable.
참고URL : https://stackoverflow.com/questions/7129285/what-is-the-purpose-of-the-return-statement
'Program Club' 카테고리의 다른 글
| CSV 파일에 UTF-8을 쓰는 방법 (0) | 2020.10.20 |
|---|---|
| ASP.NET Core에서 ILogger로 단위 테스트하는 방법 (0) | 2020.10.20 |
| wget / curl을 사용하여 주어진 웹 페이지의 .zip 파일에 대한 모든 링크를 다운로드하는 방법은 무엇입니까? (0) | 2020.10.20 |
| 바람둥이 포트 번호 변경 방법 (0) | 2020.10.20 |
| Browserify, Babel 6, Gulp-스프레드 연산자에 예기치 않은 토큰 (0) | 2020.10.20 |