一、函数定义
二、作用:提高代码的可重用性和可维护性(代码层次结构更清晰)。
三、函数返回值:
四、实例
# 定义根据月份,判断季节的方法. def get_season(month): if month < 1 or month > 12: return "输入有误" if month <= 3: return "春天" if month <= 6: return "夏天" if month <= 9: return "秋天" return "冬天" print(get_season(5)) print(get_season(15)) # 练习:定义检查列表是否具有相同元素的方法 def is_repeating(list_target): for r in range(len(list_target) - 1): for c in range(r + 1, len(list_target)): if list_target[r] == list_target[c]: return True # 退出方法(可以退出两层循环) return False re01 = is_repeating([3,44,5]) re01 = is_repeating([3,44,5,44]) print(re01) #练习:定义在控制台中显示直角三角形的函数 def print_triangle(height,char): """ 打印三角型 :param height: 三角形高度 :param char: 组成三角型的字符 :return: """ for r in range(height): for c in range(r+1): print(char, end="") print() print_triangle(8,"*") print_triangle(5,"#") print_triangle(4,"?") # 练习:定义在控制台中显示矩形的函数 def print_rect(r_count,c_count,char): for r in range(r_count):# 0 1 2 for c in range(c_count):#01234 01234 01234 print(char,end = "") # 在一行输出 print() # 换行 print_rect(2,3,"*") print_rect(5,2,"#") # 参数:变量 # 函数调用者 告诉 函数定义者的信息
原文:https://www.cnblogs.com/yuxiangyang/p/10679088.html