로봇-AI

[파이썬2강] Functions and getting help-Tutorial

happynaraepapa 2024. 12. 26. 10:22

sources:
https://www.kaggle.com/code/colinmorris/functions-and-getting-help

Functions and Getting Help

Explore and run machine learning code with Kaggle Notebooks | Using data from No attached data sources

www.kaggle.com

아래 내용은 튜토리얼의 일부를 아주 간략히 의역해 놓은 것.

You've already seen and used functions such as print and abs. But Python has many more functions, and defining your own functions is a big part of python programming.

이미 print 나 abs와 같은 함수를 써봤겠지만, 파이썬은 많은 함수가 있고, 자기만의 함수를 쓰는 것은 파이썬 프로그래밍에서 중요하다.

In this lesson, you will learn more about using and defining functions.
여기서는 함수사용법과 함수를 정의하는 방법에 대해서 배울 것.

Getting Help
You saw the abs function in the previous tutorial, but what if you've forgotten what it does?
앞서 abs() 함수를 사용해봤다.
만약 함수의 용법이 기억나지 않는다면 어떻게 해야 하나?

The help() function is possibly the most important Python function you can learn. If you can remember how to use help(), you hold the key to understanding most other functions.
help() 함수...  다른 함수의 용법에 대해 알려준다.

Here is an example:
예시)

>> help(round)

Help on built-in function round in module builtins:

round(number, ndigits=None)
    Round a number to a given precision in decimal digits.
    
    The return value is an integer if ndigits is omitted or None.  Otherwise
    the return value has the same type as the number.  ndigits may be negative.

help() displays two things:
help()함수는 두가지를 보여주는데,

the header of that function round(number, ndigits=None). In this case, this tells us that round() takes an argument we can describe as number. Additionally, we can optionally give a separate argument which could be described as ndigits.
우선 함수의 헤더(header)를 보여준다. 여기 round() 함수의 경우 숫자(number)와 자릿수(ndigits)라는 인자(입력값; argument)를 가지고 있다는 것을 보여준다.


A brief English description of what the function does.
그리고,
간단히 함수의 기능에 대해서 설명해 준다.

Common pitfall: when you're looking up a function, remember to pass in the name of the function itself, and not the result of calling that function.
한가지 주의할 점 /문제점은 함수를 넣을때, 함수 이름만 넣어야 하고, 함수의 결과값을 넣으면 안된다는 것이다.

What happens if we invoke help on a call to the function round()? Unhide the output of the cell below to see.
만약 round() 함수 결과값을 help에 넣으면 어떻게 될까?

>>help(round(-2.01))

Python evaluates an expression like this from the inside out. First it calculates the value of round(-2.01), then it provides help on the output of that expression.
파이썬은 round(-2.01)을 먼저 계산하고 이에 대한 help를 실행하게 된다.
...
If you were looking for it, you might learn that print can take an argument called sep, and that this describes what we put between all the other arguments when we print them.
print 함수는 sep라는 인자를 넣을 수 있고, 이것은 각 프린트 되는 항목들 사이에 위치하게 됨

Defining functions
Builtin functions are great, but we can only get so far with them before we need to start defining our own functions.
빌트인 함수(미리 정의된 함수)만으로도 훌륭하지만 ... 자신만의 함수를 정의할 수도 있다.

def least_difference(a, b, c):
    diff1 = abs(a - b)
    diff2 = abs(b - c)
    diff3 = abs(a - c)
    return min(diff1, diff2, diff3)



This creates a function called least_difference, which takes three arguments, a, b, and c.
least_difference라는 함수를 만들었고, 여기에는 a,b,c의 인자가 들어간다.

Functions start with a header introduced by the def keyword. The indented block of code following the : is run when the function is called.
'def' 키워드와 함께 함수 정의를 시작하고,  ':' 다음 줄에 들여쓰기 된 내용이 함수를 불렀을때 실행되는 내용들임.

return is another keyword uniquely associated with functions. When Python encounters a return statement, it exits the function immediately, and passes the value on the right hand side to the calling context.
'return' 키워드는 함수에서 사용되는 키워드로 함수가 실행되다가 return을 만나면 함수는 즉각적으로 종료되고 return 오른쪽에 기술된 값을 돌려주게 된다.

>>
print(
    least_difference(1, 10, 100),
    least_difference(1, 10, 10),
    least_difference(5, 6, 7), # Python allows trailing commas in argument lists. How nice is that?
)
>>
9 0 1


help 함수도 사용해보자.
>>
help(least_difference)
>>
Help on function least_difference in module __main__:

least_difference(a, b, c)

Python isn't smart enough to read my code and turn it into a nice English description. However, when I write a function, I can provide a description in what's called the docstring.
파이썬은 자동으로 내 함수를 읽어서 의미를 알려주지는 않지만, 미리 함수 내에 요청시 보내줄 내용(docstring)을 제공해줄 수 있다.


The docstring is a triple-quoted string (which may span multiple lines) that comes immediately after the header of a function. When we call help() on a function, it shows the docstring.
docstring은 큰따옴표 3개로 감싸져 있고, 함수 헤더 다음에 바로 온다.
만약 우리가 he[p 함수를 사용하면 docstring 도 같이 표기 된다.

Aside: The last two lines of the docstring are an example function call and result. (The >>> is a reference to the command prompt used in Python interactive shells.) Python doesn't run the example call - it's just there for the benefit of the reader. ...
참고로:
docstring의 마지막 두줄은 함수 사용 예시와 결과를 보여준다. >>>은 파이썬 쉘에서의 명령어 프롬프트에 해당한다. 파이썬은 이 예제를 진짜 실행하지는 않지만, 사용자가 함수를 이해하는데 도움을 준다....

Functions that don't return
What would happen if we didn't include the return keyword in our function?
만약 우리가 return 키워드를 함수에 사용하지 않으면 어떻게 될까?

def least_difference(a, b, c):
    """Return the smallest difference between any two numbers
    among a, b and c.
    """
    diff1 = abs(a - b)
    diff2 = abs(b - c)
    diff3 = abs(a - c)
    min(diff1, diff2, diff3)
    
print(
    least_difference(1, 10, 100),
    least_difference(1, 10, 10),
    least_difference(5, 6, 7),
)
None None None

Python allows us to define such functions. The result of calling them is the special value None. (This is similar to the concept of "null" in other languages.)
파이썬에서는 return이 없는 함수를 정의할 수 있고, 함수의 결과로 None이라는 특별한 값을 돌려주게 된다. (이것은 다른 언어의 'null'과 유사한 기능이다.)

Without a return statement, least_difference is completely pointless, but a function with side effects may do something useful without returning anything. We've already seen two examples of this: print() and help() don't return anything. We only call them for their side effects (putting some text on the screen). ...

least_difference 는 return 이 없다면 무의미해지는 함수이긴 하지만 아무것도 eturn 할 필요가 없는 함수도 있을 수 있다. 예를 들어, print()나 help()도 어떤 동작(side effect - 함수의 헤더, docstring 등의 텍스트 표시....)을 하고 있지만 자체에서 반환하는 값은 없다.


Default arguments (디폴트 인자; 기본값)

print  함수에도 많은 인자가 있다는 것을 알 수 있다.
예를들어 'sep'은 전단될 인자 사이에 구분자로 들어간다.

But if we don't specify a value, sep is treated as having a default value of ' ' (a single space).
그러나 우리가 sep값을 정하지 않는다면 싱글 스페이스가 사용된다.
이것은 sep의 기본값이 single space이기 때문.
Adding optional arguments with default values to the functions we define turns out to be pretty easy:
옵션인자의 기본값(디폴트 값0을 정의 해주는 것은 간단하다.
>>
def greet(who="Colin"):
    print("Hello,", who)
>>    
greet()
>>
greet(who="Kaggle")

# (In this case, we don't need to specify the name of the argument, because it's unambiguous.)

Functions Applied to Functions
Here's something that's powerful, though it can feel very abstract at first. You can supply functions as arguments to other functions.

우리는 함수를 다른 함수의 인자로 제공할 수도 있다.

아래 예시를 보자.
>>
def mult_by_five(x):
    return 5 * x

def call(fn, arg):
    """Call fn on arg"""
    return fn(arg)

def squared_call(fn, arg):
    """Call fn on the result of calling fn on arg"""
    return fn(fn(arg))
>>

print(
    call(mult_by_five, 1),
    squared_call(mult_by_five, 1),
    sep='\n', # '\n' is the newline character - it starts a new line
)
>>
5
25

Functions that operate on other functions are called "higher-order functions." You probably won't write your own for a little while. But there are higher-order functions built into Python that you might find useful to call.
상위 차수 함수?? 이런말 잘 안씀


Here's an interesting example using the max function.
여기에 max 함수를 이용한 재미있는 예시가 있다.

By default, max returns the largest of its arguments. But if we pass in a function using the optional key argument, it returns the argument x that maximizes key(x) (aka the 'argmax')
디폴트로 max 함수는 인자중 최대값을 리턴하지만, 추가 인자를 이용하면  key(x)를 최대로 하는 x 값을 리턴하도록 사용할 수 있다.
.
>>
def mod_5(x):
    """Return the remainder of x after dividing by 5"""
    return x % 5
>>
print(
    'Which number is biggest?',
    max(100, 51, 14),
    'Which number is the biggest modulo 5?',
    max(100, 51, 14, key=mod_5),
    sep='\n',
)

>>
Which number is biggest?
100
Which number is the biggest modulo 5?
14