Python 100天-從新手到大師學習筆記Day06:函數與模組的使用

定義函數

def factorial(num):
"""
求階乘

:param num: 非負整數
:return: num的階乘
"""
result = 1
for n in range(1, num + 1):
result *= n
return result
m = int(input('m = '))
n = int(input('n = '))

print(factorial(m) // factorial(n) // factorial(m - n))

函數的參數

def add(a=0, b=0, c=0):
return a + b + c
print(add())
print(add(1))
print(add(1, 2))
print(add(1, 2, 3))
print(add(c=50, a=100, b=200))

可變參數*args

# 在参数名前面的*表示args是一个可变参数
# 即在调用add函数时可以传入0个或多个参数
def add(*args):
total = 0
for val in args:
total += val
return total
print(add())
print(add(1))
print(add(1, 2))
print(add(1, 2, 3))
print(add(1, 3, 5, 7, 9))

重複的函數名稱該怎麼辦?

module1.pydef foo():
print('hello, world!')
module2.pydef foo():
print('goodbye, world!')
#解法如下import module1 as m1
import module2 as m2
m1.foo()
m2.foo()

結論

#使用函數功能時,依照下列格式寫即可def main():
# Todo: Add your code here
pass
if __name__ == '__main__': #避免非執行情況時,電腦自己跑函式
main()

Written by

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store