Python 基础入门指南
1. 标识符 (Identifiers)
标识符是编程时使用的名字,用于给变量、函数、语句块等命名。Python 中标识符由字母、数字、下划线组成,不能以数字开头,区分大小写。
- 单下划线开头的标识符:如
_xxx,表示不能直接访问的类属性,需通过类提供的接口进行访问,不能用 from xxx import * 导入。
- 双下划线开头的标识符:如
__xx,表示私有成员。
- 双下划线开头和结尾的标识符:如
__xx__,表示 Python 中内置标识,例如 __init__() 表示类的构造函数。
class MyClass:
def __init__(self):
self.__private = 0
self._protected = 1
2. 关键字 (Keywords)
下表列出了 Python 中的关键字(保留字),我们在自定义标识符时不能使用这些词。
常见关键字包括:False, None, True, and, as, assert, break, class, continue, def, del, elif, else, except, finally, for, from, global, if, import, in, is, lambda, nonlocal, not, or, pass, raise, return, try, while, with, yield。
3. 引号与字符串
Python 可以使用单引号 (')、双引号 (")、三引号 (''' 或 """) 来表示字符串。引号的开始与结束须类型相同,三引号可以由多行组成。
str1 = 'Hello World'
str2 = "Hello World"
str3 = '''This is a
multi-line string'''
print(str1, str2, str3)
4. 编码
- Python 2:默认编码为 ASCII,假如内容为汉字,不指定编码便不能正确输出及读取。可以通过文件头
# -*- coding: UTF-8 -*- 进行指定。
- Python 3:默认编码为 UTF-8,因此在使用 Python 3 时,通常不需要显式指定编码。
5. 输入输出
Python 输出使用 print(),内容加在括号中即可。支持格式化输出。
name = "Alice"
age = 25
print(f"Name: {name}, Age: {age}")
Python 提供了一个 input(),可以让用户输入字符串,并存放到一个变量里。
user_input = input("Please enter your name: ")
print(f"Hello, {user_input}")
6. 缩进
Python 不使用 {} 来控制类、函数、逻辑判断等,而是使用缩进。缩进的空格数可变,但同一代码块内必须保持一致。通常推荐使用 4 个空格。
if True:
print("This is indented")
if False:
print("Nested indent")
7. 多行语句
Python 中一般以新行作为语句的结束标识,可以使用反斜杠 \ 将一行语句分为多行显示。如果包含在 []、{}、() 括号中,则不需要使用反斜杠。
long_string = "This is a very long string that " \\
"needs to be split across lines"
list_data = [
1,
2,
3
]
8. 注释
Python 中单行注释使用 #,多行注释使用三个单引号 (''') 或三个双引号 (""")。
"""
This is a multi-line comment.
It can span multiple lines.
"""
def example():
pass
9. 数据类型
- 整数 (int):可以为任意大小,包含负数。
- 浮点数 (float):即小数。
- 字符串 (str):以单引号、双引号、三引号括起来的文本。
- 布尔 (bool):只有
True、False 两种值。
- 空值 (NoneType):用
None 表示。
- 变量:是可变的引用。
- 常量:在 Python 中通常指不可变对象(如元组、字符串)。
a = 10
b = 3.14
c = "Text"
d = True
e = None
10. 运算符
常用运算符包括算术运算符 (+, -, *, /, //, %, **)、比较运算符 (==, !=, >, <, >=, <=)、逻辑运算符 (and, or, not)、赋值运算符 (=, +=, -=) 等。注意运算符优先级。
x = 10 + 5 * 2
y = not (True and False)
11. 条件语句
在进行逻辑判断时,我们需要用到条件语句。Python 提供了 if、elif、else 来进行逻辑判断。
score = 85
if score >= 90:
grade = 'A'
elif score >= 80:
grade = 'B'
else:
grade = 'C'
print(f"Grade: {grade}")
12. 循环语句
当需要多次重复执行时,我们要用到循环语句。Python 提供了 for 循环和 while 循环。
For 循环
for 循环可以遍历任何序列,比如列表、字符串、元组等。
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
While 循环
while 循环满足条件时进行循环,不满足条件时退出循环。
count = 0
while count < 5:
print(count)
count += 1
Break 与 Continue
- break:用在
for 循环和 while 循环语句中,用来终止整个循环。
- continue:用在
for 循环和 while 循环语句中,用来终止本次循环,进入下一次迭代。
for i in range(10):
if i == 5:
break
print(i)
for i in range(10):
if i % 2 == 0:
continue
print(i)
Pass 语句
pass 是空语句,它不做任何事情,一般用作占位语句,作用是保持程序结构的完整性。例如在定义函数或类时暂时未实现具体逻辑。
def future_function():
pass
总结
掌握上述基础语法是学习 Python 的关键。理解标识符规则、数据类型、控制流结构以及运算符优先级,能够帮助初学者编写出正确的 Python 代码。在实际开发中,应遵循 PEP 8 规范,保持代码整洁易读。