-
[Python tutorial] 14. Functions코딩/Python 2022. 12. 21. 17:15728x90
Functions
def my_function(): print("Hello from a function") my_function() # call a function
Arguments (args)
def my_function(fname): print(fname + " Refsnes") my_function("Emil")
Number of Arguments
def my_function(fname, lname): # 2 args print(fname + " " + lname) my_function("Emil", "Refsnes") # 2 args
Arbitrary Arguments, *args
tuple of args
def my_function(*kids): print("The youngest child is " + kids[2]) my_function("Emil", "Tobias", "Linus")
Keyword Arguments, kwargs
key = value
def my_function(child3, child2, child1): print("The youngest child is " + child3) my_function(child1 = "Emil", child2 = "Tobias", child3 = "Linus")
Arbitrary Keyword Arguments, **kwargs
dictionary of arguments
def my_function(**kid): print("His last name is " + kid["lname"]) my_function(fname = "Tobias", lname = "Refsnes")
Default Parameter Value
def my_function(country = "Norway"): print("I am from " + country) my_function("Sweden") my_function()
Passing a List as an Argument
def my_function(food): for x in food: print(x) fruits = ["apple", "banana", "cherry"] my_function(fruits)
Return Values: return
def my_function(x): return 5 * x print(my_function(3))
pass
def myfunction(): pass
Recursion
defined function can call itself
def tri_recursion(k): if(k > 0): result = k + tri_recursion(k - 1) print(result) else: result = 0 return result print("\n\nRecursion Example Results") tri_recursion(6) # result = k: 6 + ( # result = 6+15 = 21 & code end # result = k: 5 + ( # result = 5+10 = 15 # result = k: 4 + ( # result = 4+6 = 10 # result = k: 3 + ( # result = 3+3 = 6 # result = k: 2 + ( # result = 2+1 = 3 # result = k: 1 + ( # result = 1 # result = k: 0 -> no print)
Recursion Example Results
1
3
6
10
15
21728x90'코딩 > Python' 카테고리의 다른 글
[Python tutorial] 16. Classes, Objects and Inheritance (1) 2022.12.21 [Python tutorial] 15. Lambda (0) 2022.12.21 [Python tutorial] 13. Control flow, Loop, Iterator (0) 2022.12.21 [Python tutorial] 12. Control flow, If...else (0) 2022.12.21 [Python tutorial] 11. Operators (0) 2022.12.21