python常用语法

Python 是一种非常流行的编程语言,因其简洁和易读性而备受欢迎。以下是一些 Python 的常用语法,涵盖基本语法、数据类型、控制流、函数、类和模块等内容。

1. 基本语法

1.1 打印输出

print("Hello, world!")

1.2 变量赋值

x = 10
y = 20
name = "Alice"

2. 数据类型

2.1 数字

integer = 10
floating_point = 10.5

2.2 字符串

single_line = 'Hello'
multi_line = """This is a 
multi-line string."""

2.3 列表

my_list = [1, 2, 3, 4]
my_list.append(5)

2.4 元组

my_tuple = (1, 2, 3)

2.5 字典

my_dict = {"name": "Alice", "age": 25}
my_dict["age"] = 26

2.6 集合

my_set = {1, 2, 3}
my_set.add(4)

3. 控制流

3.1 条件语句

x = 10
if x > 5:
    print("x is greater than 5")
elif x == 5:
    print("x is equal to 5")
else:
    print("x is less than 5")

3.2 循环

# for 循环
for i in range(5):
    print(i)

# while 循环
count = 0
while count < 5:
    print(count)
    count += 1

4. 函数

def greet(name):
    return f"Hello, {name}!"

message = greet("Alice")
print(message)

5. 类与对象

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."

# 创建对象
alice = Person("Alice", 25)
print(alice.greet())

6. 模块和包

6.1 导入模块

import math

print(math.sqrt(16))

6.2 从模块中导入特定内容

from math import sqrt

print(sqrt(16))

6.3 自定义模块

创建一个名为 my_module.py 的文件:

# my_module.py
def add(a, b):
    return a + b

def subtract(a, b):
    return a - b

在主程序中使用这个模块:

import my_module

result = my_module.add(10, 5)
print(result)

7. 异常处理

try:
    x = 1 / 0
except ZeroDivisionError:
    print("Division by zero is not allowed")
finally:
    print("This will always execute")

8. 文件操作

# 写入文件
with open("example.txt", "w") as file:
    file.write("Hello, world!")

# 读取文件
with open("example.txt", "r") as file:
    content = file.read()
    print(content)

9. 列表推导式

squares = [x ** 2 for x in range(10)]
print(squares)

10. 常用内置函数

# 获取列表长度
print(len([1, 2, 3]))

# 最大值和最小值
print(max([1, 2, 3]))
print(min([1, 2, 3]))

# 转换数据类型
print(int("10"))
print(float("10.5"))
print(str(10))

这些是 Python 中一些最常用的语法和功能,希望对你有所帮助!如果你有任何特定的需求或者问题,请告诉我,我可以提供更详细的解答。

posted @ 2024-06-04 09:19  东岸  阅读(159)  评论(0)    收藏  举报