Python函数与类入门:从基础到实践

本教程将引导你学习Python函数和类的基本概念,并提供丰富的代码示例帮助理解。

1. 函数:定义代码块,实现特定功能

函数是执行特定任务的代码块,可以通过函数名重复调用。

1.1 greet函数:输出问候语pythondef greet(name): print('Hello, ' + name + '!')

greet('Alice')

输出:Hello, Alice!

1.2 get_max函数:返回两个数的最大值pythondef get_max(num1, num2): if num1 >= num2: return num1 else: return num2

result = get_max(5, 10)print(result)

输出:10

1.3 calculate_area函数:计算圆的面积pythonimport math

def calculate_area(radius): return math.pi * radius * radius

result = calculate_area(5)print(result)

输出:78.53981633974483

2. Lambda函数:简洁表达简单函数

Lambda函数是一种匿名函数,可以简洁地定义简单函数。

2.1 计算字符串长度pythonlength = lambda str: len(str)result = length('Hello')print(result)

输出:5

2.2 返回两个数的最大值pythonget_max = lambda num1, num2: num1 if num1 >= num2 else num2result = get_max(5, 10)print(result)

输出:10

3. 类:创建自定义数据类型

类是创建自定义数据类型的蓝图,可以包含属性和方法。

3.1 Student类:存储学生信息并计算成绩等级pythonclass Student: def init(self, name, age, score): self.name = name self.age = age self.score = score

def get_grade(self):        if self.score >= 90:            return 'A'        elif self.score >= 80:            return 'B'        elif self.score >= 70:            return 'C'        elif self.score >= 60:            return 'D'        else:            return 'F'

student = Student('Alice', 18, 85)result = student.get_grade()print(result)

输出:B

总结

本教程介绍了Python函数和类的基本概念和用法,并提供了丰富的代码示例。掌握这些基础知识将帮助你编写更复杂、更实用的Python程序。

Python函数与类入门教程:从问候到成绩计算

原文地址: https://www.cveoy.top/t/topic/fvVd 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录