本文共 2560 字,大约阅读时间需要 8 分钟。
Python是一种面向对象的编程语言,其语法简洁易学,社区活跃,广泛应用于Web开发、数据分析、人工智能等领域。Python的语法规则简单,支持面向对象编程,通过类和对象实现数据封装、继承和多态等功能。
if num > 10: print("num is big then 10")else: print("no one can control me") 通过if语句可以实现程序的条件执行,else用于处理不满足条件的情况。
user_input = input("please input something:")print(user_input) input()函数用于获取用户输入,可以用于实现程序与用户交互。
result = 1 or 2 and 3print(result)
逻辑运算符包括and、or、not,用于处理布尔值的逻辑关系。
result = 1 + 2 * 3print(result)
运算符的优先级决定了执行顺序,*和/优先于+和-,and优先于or。
my_list = [10, 9, 8, 7, 6, 5, 4, 3, 2, 1]print(my_list)
列表是可变序列,用于存储多个有序元素,可以通过索引访问和修改。
studentList = ["赵云", "刘备", "诸葛亮"]print(studentList[1:2])print(studentList[:2])print(studentList[:])
切片操作可以提取列表中一部分元素,支持步长和方向。
students = ["猪八戒", "张飞", "赵云", "诸葛亮"]students.append("唐僧")students.insert(2, "马超")print(students) 列表支持append()、insert()、remove()等方法,用于增删改查操作。
d = {"name": "孙悟空", "age": 18, "sex": "男"}print(d["name"], d["age"]) 字典用于存储键值对,支持快速查找特定键的值。
my_set = {10, 1, 2, 3, 4, 1, 1, 1}print(my_set, type(my_set)) 集合用于存储不可变对象,元素无序且不重复。
def my_function(): print("我的第一个函数") 函数是可执行的代码块,可以通过调用执行。
def my_sum(a, b): return a + bprint(my_sum(1, 4))
函数参数可以指定默认值和解包,支持多种传递方式。
def my_inner_fun(i): if i % 2 == 0: return True else: return Falsedef my_fun(my_list, my_function): new_list = [] for temp in my_list: if my_function(temp): new_list.append(temp) return new_listhave_list = [1, 2, 3, 4, 5, 6, 7, 8, 9]print(my_fun(have_list, my_inner_fun))
高阶函数可以接收其他函数作为参数,实现灵活的功能扩展。
class Person: def __init__(self, name): self.name = name def say_hi(self): print("你好,我是" + self.name)person = Person("陈翔")print(person.name)person.say_hi() 类用于定义对象,通过__init__方法初始化属性,方法用于实现功能。
class Rectangle: def __init__(self, width, height): self.width = width self.height = height def get_area(self): return self.width * self.height width = property() width.setter(def width(self, value)): self.width = valuerectangle = Rectangle(2, 5)print(rectangle.get_area())
通过属性和方法实现封装,子类可以继承父类的属性和方法。
try: print(10 / 0)except ZeroDivisionError: print("除零错误处理...")finally: print("异常处理后的操作...") try、except和finally用于处理异常,finally保证执行。
with open("Hello.txt", "r") as my_file: print(my_file.read()) with语句用于文件操作,自动处理文件的打开和关闭,适用于资源管理。
Python作为一门强大且易用的编程语言,其丰富的功能和简洁的语法使得开发效率极高。通过学习基础知识和实践项目,可以逐步掌握Python编程的技巧,实现更复杂的功能。
转载地址:http://czlfk.baihongyu.com/