python3的语法及入门(近7000字,耐心看包全,看完记得点赞)

1. Python3 基础语法

缩进:Python 使用缩进来表示代码块,通常使用 4 个空格。

语句:一行代码就是一个语句。

变量:不需要声明类型,直接赋值即可。

2. Python3 基本数据类型

Python 中的基本数据类型包括整数、浮点数、字符串、布尔值等。

整数 (int)

整数是没有小数部分的数字。Python 中的整数可以是正数、负数或零。

# 创建整数
a = 10
b = -5
# 基本运算
sum_ab = a + b # 加法
diff_ab = a - b # 减法
product_ab = a * b # 乘法
quotient_ab = a // b # 整除
remainder_ab = a % b # 取模(余数)
power_ab = a ** b # 幂
print(sum_ab) # 输出: 5
print(diff_ab) # 输出: 15
print(product_ab) # 输出: -50
print(quotient_ab) # 输出: -2
print(remainder_ab) # 输出: 0
print(power_ab) # 输出: 0.0001
# 类型检查
print(type(a)) # 输出: <class 'int'>

浮点数 (float)

浮点数是有小数部分的数字。Python 中的浮点数可以表示非常大或非常小的数值。

# 创建浮点数
x = 3.14
y = -2.718
# 基本运算
sum_xy = x + y # 加法
diff_xy = x - y # 减法
product_xy = x * y # 乘法
quotient_xy = x / y # 除法
power_xy = x ** y # 幂
print(sum_xy) # 输出: 0.422
print(diff_xy) # 输出: 5.858
print(product_xy) # 输出: -8.53952
print(quotient_xy) # 输出: -1.155506858130294
print(power_xy) # 输出: 0.04305006074309672
# 类型检查
print(type(x)) # 输出: <class 'float'>

字符串 (str)

字符串是由字符组成的序列。在 Python 中,字符串是不可变的,可以通过单引号 (‘) 或双引号 (“) 来定义。

# 创建字符串
greeting = "Hello, World!"
name = 'Alice'
# 字符串拼接
full_greeting = greeting + " My name is " + name
print(full_greeting) # 输出: Hello, World! My name is Alice
# 字符串格式化
age = 25
formatted_string = f"My name is {name} and I am {age} years old."
print(formatted_string) # 输出: My name is Alice and I am 25 years old.
# 使用 .format()
formatted_string_2 = "My name is {} and I am {} years old.".format(name, age)
print(formatted_string_2) # 输出: My name is Alice and I am 25 years old.
# 访问字符
print(greeting[0]) # 输出: H
# 切片
print(greeting[7:]) # 输出: World!
print(greeting[:5]) # 输出: Hello
print(greeting[3:9]) # 输出: lo, Wo
# 字符串长度
print(len(greeting)) # 输出: 13
# 字符串方法
upper_greeting = greeting.upper() # 转换为大写
lower_greeting = greeting.lower() # 转换为小写
title_greeting = greeting.title() # 每个单词首字母大写
print(upper_greeting) # 输出: HELLO, WORLD!
print(lower_greeting) # 输出: hello, world!
print(title_greeting)  # 输出: Hello, World!
# 替换子字符串
replaced_greeting = greeting.replace("World", "Python")
print(replaced_greeting) # 输出: Hello, Python!
# 类型检查
print(type(greeting)) # 输出: <class 'str'>

布尔值 (bool)

布尔值用于表示真或假。在 Python 中,布尔值只有两个:True 和 False。

# 创建布尔值
is true = True
is false = False
#布尔运算
# 逻辑与
and result = is true and is false
# 逻辑或
or result = is true or is false
not result = not is true
print(and result)#输出:False
# 逻辑非
# 输出:True
print(or result)
# 输出:False
print(not result)
# 与其他类型的转换
zero =0
non_zero =10
empty_list =[]
non_empty_list=[1,2,3]
print(bool(zero))
print(bool(non_zero))
# 输出:False
print(bool(empty_list))
print(bool(non_empty_list))
#输出:True
#输出:False
#输出:True
# 类型检查
print(type(is_true))
#输出:<class'bool'>

类型转换

有时需要将一个数据类型转换为另一个。Python 提供了多种内置函数来实现这一目的:

int():将其他类型转换为整数。
float():将其他类型转换为浮点数。
str():将其他类型转换为字符串。
boo1():将其他类型转换为布尔值。

# 类型转换
num str =“100'
num_int= int(num str) #转换为整数
num float = float(num str)
# 转换为浮点数
#输出:100
print(num int)
print(num float) #输出:100.0
#布尔值转换
zero =0
non zero =1
empty_list =[]
non_empty_list=[1,2,3]
print(bool(zero))
print(bool(non_zero))
print(bool(empty list))
#输出:False
print(bool(non_empty list))
#输出:True
#输出:False
# 输出:True
# 字符串转换
number =123
string number =str(number)
#输出:123
print(string number)

3 数据类型转换

可以使用内置函数进行数据类型转换。

可以使用内置函数进行数据类型转换。
int():将其他类型转换为整数。
float():将其他类型转换为浮点数。
str():将其他类型转换为字符串。
bool():将其他类型转换为布尔值。

num str =“100'
# 转换为整数!
num_int = int(num_str)
# 转换为浮点数
num float = float(num str)
#输出:
print(type(num_int))
print(type(num_float))
#输出:
bool value = bool(0)
#转换为布尔值
print(bool_value)
#输出:False

4. Python3 解释器

Python 解释器是运行 Python 代码的程序。可以通过命令行或集成开发环境(IDE)使用。命令行:

python -c "print('Hello, World!')"

交互模式:

>>> print("Hello, World!")Hello, World!

5. Python3 注释

注释用于解释代码,不会被解释器执行。
单行注释:使用 #。
多行注释:使用三引号 ”’ 或 “””。

#这是一个单行注释
print("Hello, World!")
"""
这是多行注释
可以跨越多行
"""
print("这是一个多行注释的例子")

6. Python3 运算符

运算符用于执行各种操作,如算术运算、比较、逻辑运算等。算术运算符:+, -, *, /, %, //, **比较运算符:==, !=, >, <, >=, <=逻辑运算符:and, or, not位运算符:&, |, ^, ~, <<, >>a = 10b = 3# 算术运算符print(a + b) # 加法print(a – b) # 减法print(a * b) # 乘法print(a / b) # 除法print(a % b) # 取模print(a // b) # 整除print(a ** b) # 幂# 比较运算符print(a == b) # 等于print(a != b) # 不等于print(a > b) # 大于print(a < b) # 小于print(a >= b) # 大于等于print(a <= b) # 小于等于# 逻辑运算符print(a > 0 and b > 0) # 与print(a > 0 or b > 0) # 或print(not (a > 0)) # 非7. Python3 数字 (Number)数字类型包括整数、浮点数和复数。整数 (int):浮点数 (float):复数 (complex):a = 10 # intb = 3.14 # floatc = 2 + 3j # complexprint(type(a)) # 输出:print(type(b)) # 输出:print(type(c)) # 输出:‍8. Python3 字符串字符串是由字符组成的序列,支持多种操作。创建字符串:使用单引号 ‘ ‘ 或双引号 ” “。访问字符:通过索引访问。切片:获取子字符串。常用方法:len(), upper(), lower(), strip(), split(), join() 等。s = “Hello, World!”# 访问字符print(s[0]) # 输出: H# 切片print(s[0:5]) # 输出: Hello# 字符串长度print(len(s)) # 输出: 13# 转换大小写print(s.upper()) # 输出: HELLO, WORLD!print(s.lower()) # 输出: hello, world!# 去除空白s_with_spaces = ” Hello, World! “print(s_with_spaces.strip()) # 输出: Hello, World!# 分割字符串words = s.split(“, “)print(words) # 输出: [‘Hello’, ‘World!’]# 连接字符串joined = “-“.join(words)print(joined) # 输出: Hello-World!9. Python3 列表列表是有序的可变集合。创建列表:使用方括号 []。访问元素:通过索引访问。修改元素:通过索引修改。常用方法:append(), extend(), insert(), remove(), pop(), sort(), reverse() 等。fruits = [“apple”, “banana”, “cherry”]# 访问元素print(fruits[0]) # 输出: apple# 修改元素fruits[0] = “orange”print(fruits) # 输出: [‘orange’, ‘banana’, ‘cherry’]# 添加元素fruits.append(“grape”)print(fruits) # 输出: [‘orange’, ‘banana’, ‘cherry’, ‘grape’]# 插入元素fruits.insert(1, “kiwi”)print(fruits) # 输出: [‘orange’, ‘kiwi’, ‘banana’, ‘cherry’, ‘grape’]# 删除元素fruits.remove(“banana”)print(fruits) # 输出: [‘orange’, ‘kiwi’, ‘cherry’, ‘grape’]# 排序fruits.sort()print(fruits) # 输出: [‘cherry’, ‘grape’, ‘kiwi’, ‘orange’]10. Python3 元组元组是有序的不可变集合。创建元组:使用圆括号 ()。访问元素:通过索引访问。元组是不可变的:不能修改、添加或删除元素。coordinates = (10, 20)# 访问元素print(coordinates[0]) # 输出: 10# 元组解包x, y = coordinatesprint(x, y) # 输出: 10 2011. Python3 字典字典是键值对的无序集合。创建字典:使用花括号 {}。访问元素:通过键访问。修改元素:通过键修改。常用方法:keys(), values(), items(), get(), update(), pop(), clear() 等。person = { “name”: “Alice”, “age”: 25, “city”: “New York”}# 访问元素print(person[“name”]) # 输出: Alice# 修改元素person[“age”] = 26print(person) # 输出: {‘name’: ‘Alice’, ‘age’: 26, ‘city’: ‘New York’}# 添加元素person[“email”] = “alice@example.com”print(person) # 输出: {‘name’: ‘Alice’, ‘age’: 26, ‘city’: ‘New York’, ’email’: ‘alice@example.com’}# 删除元素del person[“city”]print(person) # 输出: {‘name’: ‘Alice’, ‘age’: 26, ’email’: ‘alice@example.com’}# 获取所有键print(person.keys()) # 输出: dict_keys([‘name’, ‘age’, ’email’])# 获取所有值print(person.values()) # 输出: dict_values([‘Alice’, 26, ‘alice@example.com’])# 获取所有键值对print(person.items()) # 输出: dict_items([(‘name’, ‘Alice’), (‘age’, 26), (’email’, ‘alice@example.com’)])12. Python3 集合集合是无序的不重复元素集合。创建集合:使用花括号 {} 或 set() 函数。添加元素:使用 add() 方法。删除元素:使用 remove() 或 discard() 方法。常用方法:union(), intersection(), difference(), issubset(), issuperset() 等。fruits = {“apple”, “banana”, “cherry”}# 添加元素fruits.add(“orange”)print(fruits) # 输出: {‘banana’, ‘cherry’, ‘apple’, ‘orange’}# 删除元素fruits.remove(“banana”)print(fruits) # 输出: {‘cherry’, ‘apple’, ‘orange’}# 集合运算set1 = {1, 2, 3}set2 = {3, 4, 5}# 并集print(set1.union(set2)) # 输出: {1, 2, 3, 4, 5}# 交集print(set1.intersection(set2)) # 输出: {3}# 差集print(set1.difference(set2)) # 输出: {1, 2}13. Python3 条件控制条件控制用于根据条件执行不同的代码块。if 语句:elif 语句:else 语句:age = 20if age < 18: print(“未成年”)elif age >= 18 and age < 60: print(“成年”)else: print(“老年”)14. Python3 循环语句循环用于重复执行一段代码。for 循环:遍历序列(如列表、元组、字符串等)。while 循环:在条件为真时重复执行。# for 循环fruits = [“apple”, “banana”, “cherry”]for fruit in fruits: print(fruit)# while 循环count = 0while count < 5: print(count) count += 115. Python3 编程第一步编写一个简单的程序,打印 “Hello, World!”。print(“Hello, World!”)
16. Python3 推导式推导式是一种简洁的方式,用于生成列表、字典和集合。列表推导式:字典推导式:集合推导式:# 列表推导式squares = [x ** 2 for x in range(10)]print(squares) # 输出: [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]# 字典推导式squares_dict = {x: x ** 2 for x in range(10)}print(squares_dict) # 输出: {0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81}# 集合推导式squares_set = {x ** 2 for x in range(10)}print(squares_set) # 输出: {0, 1, 64, 4, 36, 9, 16, 81, 49, 25}
17. Python3 迭代器与生成器迭代器和生成器用于处理大量数据时节省内存。迭代器:实现了 __iter__ 和 __next__ 方法的对象。生成器:使用 yield 关键字定义的函数。# 迭代器my_list = [1, 2, 3]my_iter = iter(my_list)print(next(my_iter)) # 输出: 1print(next(my_iter)) # 输出: 2print(next(my_iter)) # 输出: 3# 生成器def generate_numbers(n): for i in range(n): yield igen = generate_numbers(5)for num in gen: print(num) # 输出: 0 1 2 3 4
18. Python3 函数函数是组织代码的一种方式,可以重用代码。定义函数:使用 def 关键字。调用函数:使用函数名加括号。参数:可以传递参数给函数。返回值:使用 return 语句返回值。def greet(name): return f”你好, {name}!”print(greet(“Alice”)) # 输出: 你好, Alice!19. Python3 lambdalambda 表达式是一种简洁的定义匿名函数的方式。# 定义 lambda 函数add = lambda x, y: x + yprint(add(3, 5)) # 输出: 820. Python3 装饰器装饰器是一种特殊类型的函数,用于修改其他函数的功能或行为。def my_decorator(func): def wrapper(): print(“Something is happening before the function is called.”) func() print(“Something is happening after the function is called.”) return wrapper@my_decoratordef say_hello(): print(“Hello!”)say_hello()
21. Python3 数据结构Python 提供了多种内置的数据结构,如列表、元组、字典和集合。列表:有序的可变集合。元组:有序的不可变集合。字典:键值对的无序集合。集合:无序的不重复元素集合。‍
列表 (List)列表是有序的可变集合。可以包含不同类型的元素,并且支持索引和切片操作。# 创建列表my_list = [1, 2, 3, ‘four’, 5.0]# 访问元素print(my_list[0]) # 输出: 1print(my_list[-1])  # 输出: 5.0
# 修改元素my_list[3] = ‘FOUR’print(my_list) # 输出: [1, 2, 3, ‘FOUR’, 5.0]# 添加元素my_list.append(‘six’)print(my_list) # 输出: [1, 2, 3, ‘FOUR’, 5.0, ‘six’]# 插入元素my_list.insert(2, ‘two-and-a-half’)print(my_list)  # 输出: [1, 2, ‘two-and-a-half’, 3, ‘FOUR’, 5.0, ‘six’]
# 删除元素del my_list[2]print(my_list) # 输出: [1, 2, 3, ‘FOUR’, 5.0, ‘six’]# 切片sliced_list = my_list[1:4]print(sliced_list)  # 输出: [2, 3, ‘FOUR’]
# 列表推导式squares = [x ** 2 for x in range(5)]print(squares)  # 输出: [0, 1, 4, 9, 16]元组 (Tuple)元组是有序的不可变集合。一旦创建,其内容不能被修改。通常用于表示固定的数据集。# 创建元组my_tuple = (1, 2, 3, ‘four’, 5.0)
# 访问元素print(my_tuple[0]) # 输出: 1print(my_tuple[-1]) # 输出: 5.0# 元组解包a, b, c, d, e = my_tupleprint(a, b, c, d, e) # 输出: 1 2 3 four 5.0# 合并元组tuple1 = (1, 2)tuple2 = (3, 4)combined_tuple = tuple1 + tuple2print(combined_tuple)  # 输出: (1, 2, 3, 4)
# 元组中的嵌套nested_tuple = ((1, 2), (3, 4))print(nested_tuple[0][1]) # 输出: 2# 元组推导式(生成器表达式)squares = tuple(x ** 2 for x in range(5))print(squares)  # 输出: (0, 1, 4, 9, 16)字典 (Dictionary)字典是键值对的无序集合。每个键都是唯一的,并且关联着一个值。# 创建字典my_dict = { ‘name’: ‘Alice’, ‘age’: 25, ‘city’: ‘New York’}
# 访问元素print(my_dict[‘name’])  # 输出: Alice
# 修改元素my_dict[‘age’] = 26print(my_dict) # 输出: {‘name’: ‘Alice’, ‘age’: 26, ‘city’: ‘New York’}
# 添加元素my_dict[’email’] = ‘alice@example.com’print(my_dict) # 输出: {‘name’: ‘Alice’, ‘age’: 26, ‘city’: ‘New York’, ’email’: ‘alice@example.com’}
# 删除元素del my_dict[‘city’]print(my_dict) # 输出: {‘name’: ‘Alice’, ‘age’: 26, ’email’: ‘alice@example.com’}
# 检查键是否存在if ’email’ in my_dict:    print(“Email exists”)  # 输出: Email exists
# 获取所有键、值和项keys = my_dict.keys()values = my_dict.values()items = my_dict.items()
print(keys) # 输出: dict_keys([‘name’, ‘age’, ’email’])print(values) # 输出: dict_values([‘Alice’, 26, ‘alice@example.com’])print(items) # 输出: dict_items([(‘name’, ‘Alice’), (‘age’, 26), (’email’, ‘alice@example.com’)])
# 字典推导式squares_dict = {x: x ** 2 for x in range(5)}print(squares_dict)  # 输出: {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}集合 (Set)集合是无序的不重复元素集合。常用于数学上的集合操作,如并集、交集和差集等。# 创建集合my_set = {1, 2, 3, 4, 5}
# 访问元素# 注意:集合是无序的,不能通过索引访问元素
# 添加元素my_set.add(6)print(my_set) # 输出: {1, 2, 3, 4, 5, 6}# 删除元素my_set.remove(3)print(my_set) # 输出: {1, 2, 4, 5, 6}# 集合运算set1 = {1, 2, 3, 4}set2 = {3, 4, 5, 6}
# 并集union_set = set1.union(set2)print(union_set) # 输出: {1, 2, 3, 4, 5, 6}# 交集intersection_set = set1.intersection(set2)print(intersection_set) # 输出: {3, 4}# 差集difference_set = set1.difference(set2)print(difference_set)  # 输出: {1, 2}
# 对称差集symmetric_difference_set = set1.symmetric_difference(set2)print(symmetric_difference_set) # 输出: {1, 2, 5, 6}# 子集和超集print(set1.issubset(union_set)) # 输出: Trueprint(union_set.issuperset(set1)) # 输出: True# 集合推导式squares_set = {x ** 2 for x in range(5)}print(squares_set)  # 输出: {0, 1, 4, 9, 16}22. Python3 模块模块是包含 Python 代码的文件,可以导入并在其他文件中使用。导入模块:使用 import 关键字。从模块导入特定内容:使用 from … import …。# 导入整个模块import mathprint(math.sqrt(16)) # 输出: 4.0# 从模块导入特定内容from datetime import datetimenow = datetime.now()print(now) # 输出: 当前日期和时间23. Python3 输入和输出输入:使用 input() 函数获取用户输入。输出:使用 print() 函数输出内容。name = input(“请输入你的名字: “)print(f”你好, {name}!”)24. Python3 File文件操作用于读写文件。打开文件:使用 open() 函数。读取文件:使用 read() 或 readline() 方法。写入文件:使用 write() 方法。关闭文件:使用 close() 方法。# 写入文件with open(“example.txt”, “w”) as file: file.write(“Hello, World!\n”)# 读取文件with open(“example.txt”, “r”) as file: content = file.read() print(content) # 输出: Hello, World!25. Python3 OSos 模块提供了许多操作系统相关的功能。获取当前工作目录:使用 os.getcwd()。列出目录中的文件:使用 os.listdir()。创建目录:使用 os.mkdir()。删除目录:使用 os.rmdir()。import os# 获取当前工作目录current_dir = os.getcwd()print(current_dir)# 列出目录中的文件files = os.listdir(“.”)print(files)# 创建目录os.mkdir(“new_folder”)# 删除目录os.rmdir(“new_folder”)26. Python3 错误和异常错误和异常处理用于捕获和处理程序中的错误。try-except:捕获异常。finally:无论是否发生异常,都会执行。raise:手动抛出异常。try: result = 10 / 0except ZeroDivisionError: print(“除零错误”)finally: print(“无论是否发生异常,都会执行这里”)# 手动抛出异常raise ValueError(“这是一个自定义的错误”)27. Python3 面向对象面向对象编程(OOP)是一种编程范式,通过类和对象来组织代码。类:使用 class 关键字定义。对象:类的实例。属性:类的变量。方法:类的函数。class Person: def __init__(self, name, age): self.name = name self.age = age def greet(self): print(f”Hello, my name is {self.name} and I am {self.age} years old.”)# 创建对象person = Person(“Alice”, 25)# 访问属性print(person.name) # 输出: Alice# 调用方法person.greet() # 输出: Hello, my name is Alice and I am 25 years old.28. Python3 命名空间/作用域命名空间和作用域决定了变量的可见性和生命周期。全局命名空间:全局变量。局部命名空间:局部变量。嵌套作用域:内部函数可以访问外部函数的变量。x = 10 # 全局变量def outer_function(): y = 20 # 局部变量 def inner_function(): z = 30 # 局部变量 print(z) # 输出: 30 print(y) # 输出: 20 print(x) # 输出: 10 inner_function()outer_function()29. Python3 标准库概览Python 标准库提供了大量的模块和函数,涵盖了各种常见的任务。os:操作系统接口。sys:系统相关功能。math:数学函数。datetime:日期和时间处理。random:随机数生成。re:正则表达式。json:JSON 编码和解码。import osimport sysimport mathimport datetimeimport randomimport reimport json# 示例print(os.getcwd())print(sys.version)print(math.pi)print(datetime.datetime.now())print(random.randint(1, 10))print(re.match(r’\d+’, ‘123abc’))print(json.dumps({“name”: “Alice”, “age”: 25}))

免责申明:以上文章或网盘资源均由第三方注册用户发表,不代表本站观点,如遇侵权,请与我们联系!
寻找资源网博客 » python3的语法及入门(近7000字,耐心看包全,看完记得点赞)

发表回复

提供最优质的资源集合

立即查看 了解详情