python练习---函数定义、调用

本文介绍了Python中函数的定义与调用,通过示例代码详细讲解了如何创建函数并返回结果。提供了三个练习,包括打印一维列表、二维列表以及封装不同功能的函数,强调了return在函数中的作用,提倡通过定义辅助函数优化代码结构,提高代码可读性。

理解函数定义与调用:

# 需求: 定义函数,两个数值相加.

# 违反了"单一原则":一个函数只做一件事情.
# 函数定义者
# def add():
#     # 获取输入
#     number_one = float(input("请输入第一个数字:"))
#     number_two = float(input("请输入第二个数字:"))
#     # 逻辑处理
#     result = number_one + number_two
#     # 显示结果
#     print("结果是:%f" % result)

# 函数调用者
# add()

# 函数定义者

def add(number_one, number_two):
# 逻辑处理
result = number_one + number_two
return result # 返回结果

# 函数调用者
# 获取输入
# number_one = float(input("请输入第一个数字:"))
# number_two = float(input("请输入第二个数字:"))

re = add(50, 80)
print(re)

练习:

# 练习1: 排列出所有扑克牌 13 * 4  --> 列表(52)
# 扑克牌的数字
list_number = ["A", "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K"]
# 扑克牌的花色
list_suit = ["红桃", "黑桃", "方片", "梅花"]

list_poker = [(number, suit) for number in list_number for suit in list_suit]
print(len(list_poker), list_poker)
练习2:排列出3个色子可以组成的所有数字6 * 6 × 6   --》 6**n
# 色子(1 -- 6)  6
list_result = []
for x in range(1, 7):
    for y in range(1, 7):
        for z in range(1, 7):
            list_result.append((x, y, z))

# list_result = [(x, y, z) for x in range(1, 7) for y in range(1, 7) for z in range(1, 7)]
print(len(list_result), list_result)

“”"
练习1:定义函数,将一维列表打印在终端(一行).
测试用例 [1,3,4,5] --> 1 3 4 5
“”"

def print_list(list_target, str_end_char):
    """
        打印一维列表
    :param list_target:需要打印的一维列表
    :param str_end_char:每个元素结束时使用的字符
    """
    for item in list_target:
        print(item, end=str_end_char)
    print()

list01 = [1, 3, 4, 5]
print_list(list01, " ")

“”"
练习3:定义函数,将二维列表打印在终端(行列).
测试用例
[
[1,2,3], 1 2 3
[5,3,6] 5 3 6
]
“”"

def print_double_list(list_target, str_end_char):
    """
        打印二维列表
    :param list_target:需要打印的二维列表
    :param str_end_char: 元素结束时的字符
    """

    # 遍历二维列表,得到的是一维列表(行)
    for list_row in list_target:
        for item in list_row:
            print(item, end=str_end_char)
        print()
    print()


list01 = [
    [1, 2, 3],
    [5, 3, 6]
]
print_double_list(list01, "\t")

“”"
练习1: 将以下功能,封装到函数中。

# 在终端中获取一个四位整数,计算每位相加和.
str_number = input("请输入整数:")
result = 0
for item in str_number:
    result += int(item)
print(result)

“”"

def each_unit_sum(str_number):
    """
        遍历字符串类型整数的每位,然后求和.
    :param str_number:需要计算的str类型的整数
    :return: 求和的结果
    """
    result = 0
    for item in str_number:
        result += int(item)
    return result

re = each_unit_sum("12345")
print(re)
print(each_unit_sum("657"))

“”"
练习2: 将day03/exercise05功能,封装到函数中。
score = float(input(“请输入成绩:”))
if score > 100 or score <0:
print(“输入有误”)
elif 90 <= score:
print(“优秀”)
elif 80 <= score:
print(“良好”)
elif 60 <= score:
print(“及格”)
else:
print(“不及格”)
“”"

def calculate_score_level(score):
    if score > 100 or score <0:
        return "输入有误"
    elif 90 <= score:
        return "优秀"
    elif 80 <= score:
        return "良好"
    elif 60 <= score:
        return "及格"
    else:
        return "不及格"
print(calculate_score_level(33)

return有两种功能:1、返回数据2、退出函数
利用return的退出函数功能,将代码简化如下:

def calculate_score_level(score):
    """

    :param score:
    :return:
    """
    if score > 100 or score < 0:
        return "输入有误"#去掉了elif,也可往下执行,因为return可以退出函数,往下执行
    if 90 <= score:
        return "优秀"
    if 80 <= score:
        return "良好"
    if 60 <= score:
        return "及格"

    return "不及格"


print(calculate_score_level(86))

“”"
练习3: 将day05/exercise07功能,封装到函数中。

year = int(input("请输入年份:"))
month = int(input("请输入月份:"))
if month < 1 or month > 12:
    print("月份有误")
elif month == 2:
    if year % 4 == 0 and year % 100 != 0 or year % 400 == 0:
        print("29天")
    else:
        print("28天")
elif month in (4,6,9,11):
    print("30天")
else:
    print("31天")

“”"
优化代码,使代码条理清晰
这个主要目的是计算天数,所以判断是否为闰年应为计算天数时用到的东西,单独定义函数,使代码更易读

#优化代码,使代码条理清晰
#这个主要目的是计算天数,所以判断是否为闰年应为计算天数时用到的东西,单独定义函数,使代码更易读
def is_leap_year(year):
    # if year % 4 == 0 and year % 100 != 0 or year % 400 == 0:
    #     return True
    # else:
    #     return False
    return year % 4 == 0 and year % 100 != 0 or year % 400 == 0


# 返回值类型应该是整数(天)
# 返回值类型应该是一种(可以返回不可能的数值)
def calculate_day_by_month(year, month):
    if month < 1 or month > 12:
        return 0
    if month == 2:
        # if is_leap_year(year):
        #     return 29
        # else:
        #     return 28
        return 29 if is_leap_year(year) else 28
    if month in (4, 6, 9, 11):
        return 30

    return 31

print(calculate_day_by_month(2019, 16))
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值