Python基础
本文将讲解Python的基础知识。
YouTube Video
运行"Hello World!"
1print("Hello World!")Python中的变量
在Python中,变量是具有名称的存储空间,用于在程序中保存和使用数据与信息。变量可以保存多种数据类型,并根据需要进行重新赋值。下面,我们提供了一些示例代码来演示Python中变量的基本用法。
1# 1. Assigning values to variables
2# Integer type variable
3age = 25
4print("Age:", age) # Output: Age: 25
5
6# Floating-point type variable
7height = 175.5
8print("Height:", height, "cm") # Output: Height: 175.5 cm
9
10# String type variable
11name = "John"
12print("Name:", name) # Output: Name: John
13
14# Boolean type variable
15is_student = True
16print("Are you a student?", is_student) # Output: Are you a student? True
17
18# 2. Assigning values to multiple variables simultaneously
19# You can assign multiple variables at once
20x, y, z = 5, 10, 15
21print("x =", x, ", y =", y, ", z =", z) # Output: x = 5 , y = 10 , z = 15
22
23# 3. Updating the value of a variable
24# The value of a variable can be updated by reassignment
25age = 26
26print("Updated age:", age) # Output: Updated age: 26
27
28# 4. Updating multiple variables at once
29# Example of swapping values between variables
30a, b = 1, 2
31a, b = b, a
32print("a =", a, ", b =", b) # Output: a = 2 , b = 1
33
34# 5. Type conversion
35# Type conversion allows operations between different types
36count = "5" # String "5"
37count = int(count) # Convert to integer type
38print("Handling count as an integer:", count * 2) # Output: Handling count as an integer: 10
39
40# Conversion to floating-point number
41pi_approx = "3.14"
42pi_approx = float(pi_approx)
43print("Approximation of pi:", pi_approx) # Output: Approximation of pi: 3.14如所示,Python中的变量可以灵活使用。变量在使用时无需指定类型,并且可以根据需要重新赋值。此外,类型转换可以让不同数据类型之间轻松切换。
Python中的数据类型
Python有几种基本数据类型。以下是每种数据类型的说明及示例代码。
整数类型
整数类型用于处理没有小数点的整数。
1# Example of integer type
2x = 10
3print(x) # Output: 10
4print(type(x)) # Output: <class 'int'>浮点数类型
浮点数类型用于处理带小数点的数字。
1# Floating Point Number Example
2y = 3.14
3print(y) # Output: 3.14
4print(type(y)) # Output: float字符串类型
字符串类型表示一系列字符。字符串可以用单引号 ' 或双引号 " 包围。
1# Example of String
2s = "Hello, World!"
3print(s) # Output: Hello, World!
4print(type(s)) # Output: <class 'str'>布尔类型
布尔类型有两个值:true(True)和 false(False)。
1# Example of Boolean
2b = True
3print(b) # Output: True
4print(type(b)) # Output: <class 'bool'>列表类型
列表类型是一个可变的序列,可以存储多个元素,且元素可以是不同的数据类型。
1# Example of List
2lst = [1, 2, 3, "four", 5.0]
3print(lst) # Output: [1, 2, 3, 'four', 5.0]
4print(type(lst)) # Output: <class 'list'>元组类型
元组是一个可以包含多个元素的序列,其内容一旦创建便不能修改。
1# Example of Tuple
2tup = (1, "two", 3.0)
3print(tup) # Output: (1, 'two', 3.0)
4print(type(tup)) # Output: <class 'tuple'>字典类型
字典类型是一个存储键值对的集合。键必须是唯一的。
1# Example of Dictionary
2dct = {"one": 1, "two": 2, "three": 3}
3print(dct) # Output: {'one': 1, 'two': 2, 'three': 3}
4print(type(dct)) # Output: <class 'dict'>集合类型
集合类型是一个存储唯一元素的集合。不能包含重复的值。
1# Example of Set
2st = {1, 2, 2, 3}
3print(st) # Output: {1, 2, 3}
4print(type(st)) # Output: <class 'set'>这些数据类型是用于处理 Python 数据的基本类型。通过适当使用它们,您可以满足程序中的各种需求。
Python 概述
Python 是由 Guido van Rossum 于 1991 年开发的一种高级编程语言。其设计哲学强调“简单”、“清晰”和“可读性”,使代码直观、易写且易读。以下是 Python 主要功能的概述。
-
易于阅读且简单:
- 具有清晰的结构和接近自然语言的表达方式,它是初学者容易学习的语言。
- 块通过缩进定义,这会自动格式化代码并提高可读性。
-
丰富的库和框架:
- 它拥有丰富的标准库,使得许多任务可以轻松完成。
- 针对各种领域,都有专门的库和框架可用,例如数值计算(NumPy)、数据分析(Pandas)、机器学习(scikit-learn, TensorFlow)以及网页开发(Django, Flask)。
-
多功能性:
- Python 既适合作为脚本语言,也适合用于完整功能的应用开发。它广泛用于网页应用、桌面应用、科学计算、机器学习、数据分析和物联网等各种应用中。
-
跨平台:
- 它与平台无关,可以在包括 Windows、macOS 和 Linux 在内的许多操作系统上运行。
-
开源与社区:
- Python 是一个由活跃社区支持的开源项目。因此,它得到了频繁的更新、库的开发和支持。
-
动态类型与自动内存管理:
- 动态类型无需声明变量类型,从而加快了开发速度。
- 垃圾回收执行自动内存管理,使内存管理变得简单。
凭借这些功能,Python 广泛应用于教育、工业和学术等各种领域。
Python中的转义字符
在Python中,转义字符用于在字符串中包含特定的控制字符或具有特殊含义的字符。转义字符是用于为普通字符串添加特定含义的特殊符号。让我们仔细了解一下Python中的转义字符。
转义字符基础
在Python中,转义字符是通过反斜杠(\)定义的。转义字符表示在普通字符串中的特定行为。例如,\n表示换行,\t表示制表符(空格)。
您可以按如下方式定义包含转义字符的字符串:。
1# Example of escape characters
2print("Hello\nWorld") # A newline is inserted after "Hello"
3
4# Output:
5# Hello
6# World主要转义字符列表
Python中使用的主要转义字符如下:。
\\: 表示反斜杠本身。\': 在字符串中包含单引号。\": 在字符串中包含双引号。\n: 换行\t: 制表符\r: 回车\b: 退格\f: 换页\a: 警报音(铃声)\v: 垂直制表符\N{name}: 按名称从Unicode数据库获取字符\uXXXX: 16位Unicode字符(用4位十六进制数字表示)\UXXXXXXXX: 32位Unicode字符(用8位十六进制数字表示)\xXX: 由十六进制表示的字符
常用转义字符的示例
以下是一些如何使用转义字符的具体示例。
双引号和单引号
要在字符串中包含双引号或单引号,请使用转义字符。
1# String containing double quotes
2quote = "He said, \"Python is amazing!\""
3print(quote)
4
5# String containing single quotes
6single_quote = 'It\'s a beautiful day!'
7print(single_quote)
8
9# Output:
10# He said, "Python is amazing!"
11# It's a beautiful day!换行符和制表符
换行符和制表符通常用于格式化文本。
1# Example using newline
2multiline_text = "First line\nSecond line"
3print(multiline_text)
4
5# Example using tab
6tabbed_text = "Column1\tColumn2\tColumn3"
7print(tabbed_text)
8
9# Output:
10# First line
11# Second line
12# Column1 Column2 Column3Unicode 转义字符
在 Python 中,Unicode 字符使用 \u 或 \U 表示。这在处理非英语字符时特别有用。
1# Example of Unicode escape
2japanese_text = "\u3053\u3093\u306B\u3061\u306F" # Hello in Japanese
3print(japanese_text)
4# Output:
5# こんにちは(Hello in Japanese)使用特殊转义字符的注意事项
使用转义字符时,需要注意一些事项。
- 原始字符串:如果要原样显示包含反斜杠的字符串,请在字符串前加上
r。
1raw_string = r"C:\Users\name\Documents"
2print(raw_string)
3# Output:
4# C:\Users\name\Documents在原始字符串中,反斜杠不会被解释为转义字符,而是原样输出。
- 使用 Unicode:使用 Unicode 转义字符时,请确保指定的十六进制代码是正确的。不正确的规范会导致字符显示错误。
转义反斜杠
要在字符串中包含反斜杠本身,请使用双反斜杠。
1# Example containing backslash
2path = "C:\\Program Files\\Python"
3print(path)
4# Output:
5# C:\Program Files\Python高级示例:复杂字符串格式化
还可以组合转义字符以格式化复杂字符串。
1# Example of formatting a message
2message = "Dear User,\n\n\tThank you for your inquiry.\n\tWe will get back to you shortly.\n\nBest Regards,\nCustomer Support"
3print(message)
4# Output:
5# Dear User,
6#
7# Thank you for your inquiry.
8# We will get back to you shortly.
9#
10# Best Regards,
11# Customer Support总结
Python 的转义字符是一个强大的工具,用于在字符串中包含特定的控制字符或特殊字符。了解如何使用它们并根据需要合理应用,可以实现更灵活的字符串处理。
Python 版本
让我们简要回顾主要的 Python 版本及其特性。
- Python 1.0(1994 年)
1# Sample code that works in Python 1.0
2def greet(name):
3 print "Hello, " + name # print was a statement
4
5greet("World")首次正式发布。Python 的基本语法和标准库在这一版本中确立。
- Python 2.0(2000 年)
1# Sample code that works in Python 2.0
2
3# List comprehension
4squares = [x * x for x in range(5)]
5print squares
6
7# Unicode string (u"...")
8greet = u"Hello"
9print greet添加了诸如列表推导式、完整垃圾回收以及 Unicode 支持的开端等重要特性。Python 2 被使用了很长时间,但其支持于 2020 年结束。
- Python 3.0(2008 年)
1# Sample code that works in Python 3.0
2
3# print is now a function
4print("Hello, world!")
5
6# Unicode text is handled natively
7message = "Hello"
8print(message)一次重大更新,没有向后兼容。将 print 改为函数,Unicode 成为默认的字符串类型,整数类型得到了统一,大大提升了 Python 的一致性和可用性。Python 3 是当前的主流版本。
- Python 3.5 (2015)
1# Sample code that works in Python 3.5
2import asyncio
3
4async def say_hello():
5 await asyncio.sleep(1)
6 print("Hello, async world!")
7
8asyncio.run(say_hello())引入了async/await语法,使异步编程更易编写。
- Python 3.6 (2016)
1# Sample code that works in Python 3.6
2
3name = "Alice"
4age = 30
5print(f"{name} is {age} years old.") # f-string makes formatting simple添加了格式化字符串字面值(f-strings),使字符串格式化更加方便。此外,类型提示得到了扩展。
- Python 3.7 (2018)
1# Sample code that works in Python 3.7
2
3from dataclasses import dataclass
4
5@dataclass
6class Person:
7 name: str
8 age: int
9
10p = Person("Bob", 25)
11print(p)引入了数据类(dataclasses),使定义类结构更加方便。对async/await的支持也得到了增强。
- Python 3.8 (2019)
1# Sample code that works in Python 3.8
2
3# Assignment inside an expression
4if (n := len("hello")) > 3:
5 print(f"Length is {n}")添加了海象运算符(:=),支持赋值表达式的使用。还引入了仅限位置参数,提高了函数参数的灵活性。
- Python 3.9 (2020)
1# Sample code that works in Python 3.9
2
3a = {"x": 1}
4b = {"y": 2}
5c = a | b # merge two dicts
6print(c) # {'x': 1, 'y': 2}改进了类型提示,并添加了用于合并列表和字典的运算符(|)。标准库也进行了重组。
- Python 3.10 (2021)
1# Sample code that works in Python 3.10
2
3def handle(value):
4 match value:
5 case 1:
6 return "One"
7 case 2:
8 return "Two"
9 case _:
10 return "Other"
11
12print(handle(2))添加了模式匹配,支持更强大的条件语句。改进了错误消息,并进一步加强了类型系统。
- Python 3.11 (2022)
1# Sample code that works in Python 3.11
2
3# Improved performance (up to 25% faster in general)
4# More informative error messages
5try:
6 eval("1/0")
7except ZeroDivisionError as e:
8 print(f"Caught an error: {e}")做出了**显著的性能提升**,相比之前的版本执行速度更快。此外,还改进了异常处理与类型检查。
- Python 3.12 (2023)
1# Sample code that works in Python 3.12
2
3# Automatically shows exception chains with detailed traceback
4def f():
5 raise ValueError("Something went wrong")
6
7def g():
8 try:
9 f()
10 except Exception:
11 raise RuntimeError("Higher level error") # Automatically chained
12
13try:
14 g()
15except Exception as e:
16 import traceback
17 traceback.print_exception(type(e), e, e.__traceback__)错误消息进一步改进,性能增强。此外,异常链会自动显示,使调试更详细。还新增了语法特性并增强了标准库,提高了开发者的生产效率。
- Python 3.13(2024)
1# Sample code that works in Python 3.13
2
3# Using the new 'except*' syntax for handling multiple exceptions in parallel
4import asyncio
5
6async def raise_errors():
7 raise ExceptionGroup("Multiple errors", [
8 ValueError("Invalid value"),
9 TypeError("Wrong type"),
10 ])
11
12async def main():
13 try:
14 await raise_errors()
15 except* ValueError as e:
16 print("Caught ValueError(s):", e.exceptions)
17 except* TypeError as e:
18 print("Caught TypeError(s):", e.exceptions)
19
20asyncio.run(main())在 Python 3.13 中,ExceptionGroup 和 except* 语法得到了进一步完善,允许在异步处理时并行捕获多个异常。这使得在使用并行处理或 asyncio 的应用程序中进行调试和错误处理变得更加直观和强大。此外,类型提示的改进和标准库的更新提升了代码的可维护性和表达力。
Python 3 版本正在不断发展,最新版本带来了性能提升、类型系统的改进以及新功能。
您可以在我们的YouTube频道上使用Visual Studio Code跟随上述文章进行学习。 请也查看我们的YouTube频道。