Python基础—15个必知语法细节

以下是Python语言核心的15个必知语法细节,每个细节都附有相应的代码示例:

  1. 动态类型与变量赋值
a = 10        # 整数
b = 3.14      # 浮点数
c = "Hello"   # 字符串
d = [1, 2, 3] # 列表
  1. 变量命名规则
# 正确的变量名
my_variable = 10
_another_var = 20

# 错误的变量名(以数字开头)
# 1_var = 30  # SyntaxError
  1. 字符串操作
s = "Hello, World!"
print(s[0])       # 'H'(索引)
print(s[0:5])     # 'Hello'(切片)
print(s * 2)      # 'Hello, World!Hello, World!'(重复)
  1. 列表与元组
# 列表
lst = [1, 2, 3]
lst.append(4)     # [1, 2, 3, 4](修改列表)

# 元组
tup = (1, 2, 3)
# tup.append(4)  # AttributeError: 'tuple' object has no attribute 'append'(不可修改)
  1. 字典
d = {'name': 'Alice', 'age': 25}
print(d['name'])  # 'Alice'(通过键访问)
d['age'] = 26     # {'name': 'Alice', 'age': 26}(修改字典)
  1. 条件语句
x = 10
if x > 5:
    print("x is greater than 5")
else:
    print("x is 5 or less")
  1. 循环语句
# for循环
for i in range(5):
    print(i)

# while循环
count = 0
while count < 5:
    print(count)
    count += 1
  1. 函数定义与调用
def greet(name):
    return f"Hello, {name}!"

print(greet("Alice"))  # 'Hello, Alice!'
  1. 模块导入
import math
print(math.sqrt(16))  # 4.0(导入math模块并使用其sqrt函数)
  1. 异常处理
try:
    result = 10 / 0  # 这将引发一个ZeroDivisionError
except ZeroDivisionError:
    print("Cannot divide by zero!")
  1. 列表解析
squares = [x**2 for x in range(5)]
print(squares)  # [0, 1, 4, 9, 16]
  1. 生成器函数
def my_generator():
    yield 1
    yield 2
    yield 3

gen = my_generator()
for value in gen:
    print(value)  # 1, 2, 3(逐个生成值)
  1. 面向对象编程(类与对象)
class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def greet(self):
        return f"Hello, my name is {self.name} and I am {self.age} years old."

p = Person("Alice", 30)
print(p.greet())  # 'Hello, my name is Alice and I am 30 years old.'
  1. 文件操作
# 写入文件
with open('example.txt', 'w') as file:
    file.write("Hello, World!")

# 读取文件
with open('example.txt', 'r') as file:
    content = file.read()
    print(content)  # 'Hello, World!'
  1. 代码注释
# 这是一个单行注释

"""
这是一个多行注释(文档字符串)
它通常用于描述函数、类或模块的功能和用途。
"""

def example_function():
    """
    这是一个示例函数的文档字符串。
    """
    pass

这些代码示例展示了Python语言的核心语法细节,并通过实际代码帮助理解每个细节的用法。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值