Python入门必知:基础语法、数据结构、面向对象,一网打尽学习要点

基础语法
Python是一种解释型、高级编程语言,以其简洁的语法和强大的库支持而闻名。以下是一些Python的基础语法要点:
1. 变量和赋值
在Python中,变量不需要显式声明类型。变量名由字母、数字和下划线组成,且不能以数字开头。
name = “Alice”
age = 25
is_student = True
2. 数据类型
Python有几种基本数据类型,包括数字、字符串和布尔值。
数字
:整数(
int
)、浮点数(
float
)和复数(
complex
)。
字符串
:用于存储文本数据,使用引号(单引号或双引号)包围。
布尔值
:
True
或
False
。
num = 10
price = 19.99
text = ‘Hello, World!’
is_valid = True
3. 运算符
Python支持各种运算符,包括算术运算符、比较运算符和逻辑运算符。
# 算术运算符
result = 5 + 3 # 8
result = 5 – 3 # 2
result = 5 * 3 # 15
result = 5 / 3 # 1.666…
result = 5 % 3 # 2 (余数)
result = 5 ** 3 # 125 (幂)

# 比较运算符
is_equal = (5 == 5) # True
is_greater = (5 > 3) # True
is_less = (5 < 3) # False # 逻辑运算符 is_and = (True and False) # False is_or = (True or False) # True is_not = (not True) # False 4. 控制流 Python使用 if 、 elif 和 else 语句进行条件判断,以及 for 和 while 循环进行迭代。 # if语句 if age > 18:
print(“You are an adult.”)
else:
print(“You are not an adult.”)

# for循环
for i in range(5):
print(i)

# while循环
count = 0
while count < 5: print(count) count += 1 数据结构 Python提供了一系列内置的数据结构,包括列表、元组、字典和集合。 1. 列表(List) 列表是可变的数据结构,可以存储不同类型的数据。 fruits = ["apple", "banana", "cherry"] print(fruits[0]) # 输出: apple fruits[1] = "orange" print(fruits) # 输出: ['apple', 'orange', 'cherry'] 2. 元组(Tuple) 元组是不可变的数据结构,类似于列表,但一旦创建,就不能修改。 coordinates = (10, 20) print(coordinates[0]) # 输出: 10 3. 字典(Dictionary) 字典是键值对集合,其中键是唯一的。 person = {"name": "Alice", "age": 25} print(person["name"]) # 输出: Alice 4. 集合(Set) 集合是无序的不重复元素集。 numbers = {1, 2, 3, 4, 5} print(numbers) # 输出: {1, 2, 3, 4, 5} 面向对象 Python是一种面向对象的语言,支持类和对象的概念。 1. 类(Class) 类是创建对象的蓝图。 class Dog: def __init__(self, name, age): self.name = name self.age = age def bark(self): print(f"{self.name} says: Woof!") my_dog = Dog("Buddy", 5) my_dog.bark() # 输出: Buddy says: Woof! 2. 对象(Object) 对象是类的实例。 my_dog = Dog("Buddy", 5) print(my_dog.name) # 输出: Buddy 3. 继承(Inheritance) 继承允许一个类继承另一个类的属性和方法。 class Puppy(Dog): def __init__(self, name, age, color): super().__init__(name, age) self.color = color puppy = Puppy("Max", 2, "brown") print(puppy.color) # 输出: brown 4. 多态(Polymorphism) 多态是指同一个操作作用于不同的对象上可以有不同的解释,产生不同的执行结果。 class Animal: def sound(self): pass class Dog(Animal): def sound(self): return "Woof!" class Cat(Animal): def sound(self): return "Meow!" dog = Dog() cat = Cat() print(dog.sound()) # 输出: Woof! print(cat.sound()) # 输出: Meow! 通过以上内容,您应该对Python的基础语法、数据结构和面向对象有了一定的了解。这些是Python编程的基础,掌握它们将有助于您在Python编程的世界中更进一步。