023函数def

# __author__:Nzkalhbxx
# __date__:17-10-29
import time
# 函数的定义:
"""
def functionName(形参1, 形参2...):
    函数体...
"""

def eatApple():
    time_format = "%Y-%m-%d  %X"
    time_current = time.strftime(time_format)
    print("you should eat %s %s at %s"%("apple", 3, time_current))
def eatBanana():
    time_format = "%Y-%m-%d  %X"
    time_current = time.strftime(time_format)
    print("you should eat %s %s at %s"%("Banana", 7, time_current))
def eat_passion_fruit():
    time_format = "%Y-%m-%d  %X"
    time_current = time.strftime(time_format)
    print("you should eat %s %s at %s"%("passion_fruit", 11, time_current))

eatApple()
eatBanana()
eat_passion_fruit()

print("使用参数".center(33, "-"))
def eat(fruit, num, name=""):
    time_format = "%Y-%m-%d  %X"
    time_current = time.strftime(time_format)
    if name != "":
        print(name, end=", ")
    print("you should eat %s %d at %s" % (fruit, num, time_current))

# 只有当形参有默认值时可以缺省, 否则eat() missing 1 required positional argument: 'name'
eat("apple", 7)
# 当一个实参使用key = value传递参数时顺序可以随意, 但未使用k-v的参数必须写在前面
eat("banana", name="", num=3)
# 当不使用key = value时, 参数顺序必须一一对应
eat("passion_fruit", 7, "psj")
# eat("passion_fruit", "psj", 19)     # TypeError: %d format: a number is required, not str

023函数def_第1张图片
运行结果

你可能感兴趣的:(023函数def)