5. Function

2024. 3. 14. 01:13·Python
5python-functions

Functions¶

In [12]:
def my_fun1(i):
    print("in the function, here's i:" , i)
    return

my_fun1(10)
my_fun1(5)
in the function, here's i: 10
in the function, here's i: 5

Arguments¶

Note: Python passes mutable objects by reference, similar to assignment.

In [4]:
def my_fun2(i, A, B):
    i = 5
    A[0] = 5
    B = {4, 5, 6}

i = 1
A = [1, 2, 3]
B = {1, 2, 3}
my_fun2(i, A, B)
print('i={}; A={}; B={}'.format(i, A, B))
i=1; A=[5, 2, 3]; B={1, 2, 3}

This is not surprising, because passing arguments is essentially the same as assigning variables in Python.

In [5]:
i_g = 1
A_g = [1, 2, 3]
B_g = {1, 2, 3}
my_fun2(i=i_g, A=A_g, B=B_g)
print('i_g={}; A_g={}; B_g={}'.format(i_g, A_g, B_g))
i_g=1; A_g=[5, 2, 3]; B_g={1, 2, 3}

Arguments can have optional arguments, which have default values.

In [8]:
def check_answer(val, correct_answer="a", third_arg=1):
    if val == correct_answer:
        return True
    else:
        return False

print(check_answer("a"))
print(check_answer("a", third_arg=2))
True
True

It is important to note that python evaluates the mutable objects of optional arguments once: When the function is defined. This means that if you make the default an empty object, for instance, it will persist across all calls.

This is one of the most common errors for beginners

In [9]:
def f(a, L = []):
    L.append(a)
    return L

print(f(1))
print(f(2))
print(f(3))
[1]
[1, 2]
[1, 2, 3]

To re-intialize L to the empty list each time, initialize L to an immultable object instead:

In [10]:
def fnew(a, L=None):
    if L is None:
        L = []
    L.append(a)
    return L

print(fnew(1))
print(fnew(2))
print(fnew(3))
[1]
[2]
[3]

Return Values¶

Functions always return a value of any type. If one is not explicitly given, then they return None.

In [13]:
a = my_fun1(10)
print(a)
in the function, here's i: 10
None

A function can return multiple values using tuple.

In [17]:
def fib2(n): # return Fibonacci series up to n (from the python tutorial)
    """Return a list containing the Fibonacci series up to n."""
    result = []
    a, b = 0, 1
    while a < n:
        result.append(a)    # see below
        a, b = b, a+b
    return result, len(result)

#lst, n = fib2(250)
#print(n)
#print(lst)

rv = fib2(250)
print(rv[0], rv[1])
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233] 14

Namespace¶

A function has its own namespace. If a variable is not defined in the function, then it will look for the global variable in its enclosing namespace (such as the module containing the function; more later).

In [18]:
def print_fun(string, n):
    if n < global_var:
        print(string * n)
    else:
        print(string * global_var)

print_fun("-", 5)
print_fun("-", 20)
-----
----------
In [19]:
global_var = 100
In [20]:
print_fun("-", 50)
--------------------------------------------------

Docstring¶

Note that this function includes a docstring (just after the function definition). This is used by the help system.

In [21]:
help(fib2)
Help on function fib2 in module __main__:

fib2(n)
    Return a list containing the Fibonacci series up to n.

The docstring can also be modified by setting __doc__.

In [22]:
fib2.__doc__
Out[22]:
'Return a list containing the Fibonacci series up to n.'
In [23]:
fib2.__doc__ = 'Updated: Return a list containing the Fibonacci series up to n.'

help(fib2)
Help on function fib2 in module __main__:

fib2(n)
    Updated: Return a list containing the Fibonacci series up to n.

In [ ]:
 

'Python' 카테고리의 다른 글

7. Lambda Functions  (0) 2024.03.14
6. Recursion vs. Iteration  (1) 2024.03.14
4. Conditionals and Loops  (0) 2024.03.14
3. Exception Handling  (0) 2024.03.14
2. List, Set, Tuple  (1) 2024.03.14
'Python' 카테고리의 다른 글
  • 7. Lambda Functions
  • 6. Recursion vs. Iteration
  • 4. Conditionals and Loops
  • 3. Exception Handling
Juson
Juson
  • Juson
    Juson의 데이터 공부
    Juson
  • 전체
    오늘
    어제
    • 분류 전체보기 (95)
      • RAG (2)
      • AI (2)
        • NLP (0)
        • Generative Model (0)
        • Deep Reinforcement Learning (2)
        • LLM (0)
      • Logistic Optimization (0)
      • Machine Learning (37)
        • Linear Regression (2)
        • Logistic Regression (2)
        • Decision Tree (5)
        • Naive Bayes (1)
        • KNN (2)
        • SVM (2)
        • Clustering (4)
        • Dimension Reduction (3)
        • Boosting (6)
        • Abnomaly Detection (2)
        • Recommendation (4)
        • Embedding & NLP (4)
      • Reinforcement Learning (5)
      • Deep Learning (10)
        • Deep learning Bacis Mathema.. (10)
      • Optimization (2)
        • OR Optimization (0)
        • Convex Optimization (0)
        • Integer Optimization (0)
      • SNA 분석 (0)
      • 포트폴리오 최적화 공부 (0)
        • 최적화 기법 (0)
        • 금융 베이스 (0)
      • Finanancial engineering (0)
      • 프로그래머스 데브코스(Boot camp) (15)
        • SQL (9)
        • Python (5)
        • Machine Learning (1)
      • Python (22)
      • Project (0)
  • 블로그 메뉴

    • 홈
    • 태그
    • 방명록
  • 링크

  • 공지사항

  • 인기 글

  • 태그

  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.4
Juson
5. Function
상단으로

티스토리툴바