2.6 函式
基本語法架構
# Function is a group of related statements that perform a specific task.
def function_name(parameters):
statement(s)
- def
- marks the start of function header.
- function name
- to uniquely identify it.
- parameters
- through which we pass values to a function. (optional)
- colon (:)
- to mark the end of function header.
- return statement
- to return a value from the function. (optional)
定義一個簡單的Define, Call Function
無輸入參數呼叫
# define function without parameters
def greet():
print("Hello!")
# call function
greet() # Hello!
有輸入參數呼叫
# define function with parameter
def greet(name):
print("Hello", name + ", nice to meet you.")
greet("Felix") # Hello Felix, nice to meet you.
定義一個具有回傳值的函式 Return Statement
單一個回傳
# One
def add_two_nums(arg1, arg2):
sum = arg1 + arg2
return sum
# call function
result = add_two_nums(10, 20)
print(result) # 30
多個回傳值
第一種是回傳接收一組tuple
# constructs a tuple and returns this to the caller
def square(x,y):
return x*x, y*y
result = square(2,3)
print(result) # (4,9)
可以將回傳結果用變數去接收
# "unwrap" the tuple into the variables directly by specifying the same number of variables
def square(x,y):
return x*x, y*y
res_x, res_y = square(2,3)
print(res_x) # 4
print(res_y) # 9
匿名函式 Anonymous Function - Lambda
單個數入參數
# Lambda functions can have only one expression.
# The expression is evaluated and returned.
double = lambda x: x * 2
print(double(5)) # 10
# is nearly the same as
def double(x):
return x * 2
多個輸入參數
# Lambda functions can have any number of arguments
double = lambda x, y: x * 2 + y
print(double(5,2)) # 12
# is nearly the same as
def double(x, y):
return x * 2 + y
Global, Local variables
# global
x = "global"
def foo():
y = x + "_variable"
print(y)
foo() # global_variable
# local
def foo():
z = "local"
# NameError: name 'z' is not defined
print(z)
Test
Q1. 請寫出一個函式,將列表中的數字相乘。
Sample List : [1, 2, 3, 4, 5]
Expected Result : 120
def myFunction(list):
tot=1
for num in list:
tot*=num
return tot
print(myFunction([1, 2, 3, 4, 5]))
Q2. 請寫一個函式,輸入一字串,返回反轉全部字元的字串。
a_func("test")
Expected Result : "tset"
def a_func(str):
reverseStr=""
for char in range(len(str)-1,-1,-1):
reverseStr+=str[char]
return reverseStr
print(a_func('test'))
def a_func(x):
return x[::-1]
print(a_func('test'))
a_func=lambda x: x[::-1]
print(a_func('test'))
Q3. 請寫一個函式把裡面的字串,每個單字本體做反轉,但是單字的順序不變。 (Optional)
a_func("it is a test string")
Expected Result : "ti si a tset gnirts"
def a_func(str):
arr=str[::-1].split(' ')
return (' ').join(arr[::-1])
print(a_func('it is a test string'))