Python 语法
本文解释了 Python 的语法。
YouTube Video
Python 中的语法
缩进
Python 使用缩进来定义代码块。与许多使用大括号 {} 定义代码块的语言不同,Python 使用缩进。通常,缩进会使用四个空格,但也可以使用制表符。但是,您应注意不要在同一个文件中混合使用空格和制表符。
1x = 5
2if x > 0:
3 print("Positive")
4else:
5 print("Non-positive")注释
单行注释
在 Python 中,注释以 # 开始。从 # 开始直到行尾的所有内容都被视为注释。
1# This is a comment
2print("Hello, World!") # This is also a comment文档字符串(Docstring)
docstring 是一种用于描述代码的字符串,由三个双引号 """ 或三个单引号 ''' 包围。主要用于描述模块、类和函数。
1def greet(name):
2 """
3 This function displays a greeting to the specified name.
4
5 Parameters:
6 name (str): The name of the person to greet.
7 """
8 print(f"Hello, {name}!")可以通过 help() 函数查看 Docstring。
1help(greet)注释的最佳实践
注释的最佳实践包括以下几点:。
1# Good example
2# Validate user input and display a personalized message
3
4# Ask for the user's name
5name = input("Enter your name: ")
6
7# Ask for the user's age and convert it to an integer
8age = int(input("Enter your age: "))
9
10# Check eligibility based on age
11if age >= 18:
12 # Inform the user that they can register
13 print(f"Welcome, {name}! You are eligible to register.")
14else:
15 # Inform the user that they are underage
16 print(f"Sorry, {name}. You must be at least 18 years old to register.")
17
18# Bad example
19# Store the user's name in the variable 'name'
20name = input("Enter your name: ")
21
22# Convert the input to an integer and store it in 'age'
23age = int(input("Enter your age: "))
24
25# Check if the user is greater than or equal to 18
26if age >= 18:
27 # Print a welcome message
28 print(f"Welcome, {name}! You are eligible to register.")
29else:
30 # Print a rejection message
31 print(f"Sorry, {name}. You must be at least 18 years old to register.")-
清晰简洁 注释用于清楚地解释代码的意图。
-
不要重复代码的含义 避免对不言自明的代码添加注释。
-
保持一致性 在团队开发中,保持注释风格和格式的一致性是很重要的。
变量和数据类型
在 Python 中,声明变量时无需指定数据类型。数据类型会在赋值时自动确定。
1x = 10 # Integer
2y = 3.14 # Floating-point number
3name = "Alice" # String (text)
4is_active = True # Boolean value (True or False)条件语句
条件语句使用 if、elif(等同于 else if)和 else。
1x = 0
2if x > 0:
3 print("Positive")
4elif x == 0:
5 print("Zero")
6else:
7 print("Negative")循环语句
Python 提供了 for 循环和 while 循环,二者的用途不同。
for 语句
for 语句通常用于遍历列表或元组中的元素。
1fruits = ["apple", "banana", "cherry"]
2for fruit in fruits:
3 print(fruit)while 语句
while 语句在条件为真时重复执行循环。
1count = 0
2while count < 5:
3 print(count)
4 count += 1定义函数
在Python中,函数通过def关键字定义。
1def greet(name):
2 print(f"Hello, {name}!")
3
4greet("Alice")定义类
在Python中,您可以使用 class 关键字定义类,从而实现面向对象编程。
1class Dog:
2 def __init__(self, name):
3 self.name = name
4
5 def bark(self):
6 print("Woof!")
7
8dog = Dog("Fido")
9dog.bark()模块和导入
在 Python 中,import 关键词用于导入模块并访问已有代码。
1# Importing the sqrt function from the math module
2from math import sqrt
3
4result = sqrt(16)
5print(result) # Output: 4.0错误和异常处理
Python 的 try-except 结构处理错误和意外情况。
1# Catching a division-by-zero error example
2try:
3 result = 10 / 0
4except ZeroDivisionError:
5 print("Cannot divide by zero.")结论
Python的基本语法非常简单且具有很高的可读性。这些基础知识是编写Python代码的必要元素。
您可以在我们的YouTube频道上使用Visual Studio Code跟随上述文章进行学习。 请也查看我们的YouTube频道。