📜  python中的操作(1)

📅  最后修改于: 2023-12-03 15:04:36.438000             🧑  作者: Mango

Python中的操作

Python 是一个易学易用的编程语言,在数据处理、机器学习、自然语言处理、Web开发等领域被广泛应用。下面介绍 Python 中常用的操作。

基本类型操作
数字类型

Python 支持 int, float, complex 等数字类型。其中 int 表示整型,float 表示浮点型,complex 表示复数类型。可以进行基本的算术操作,如加减乘除,取余数和指数运算。例如:

a = 3
b = 2.0
c = 1 + 2j
print(a + b)  # 输出 5.0
print(a / b)  # 输出 1.5
print(a % b)  # 输出 1.0
print(b ** a) # 输出 8.0
print(c.real) # 输出 1.0
print(c.imag) # 输出 2.0
字符串类型

Python 使用单引号或双引号表示字符串类型。可以使用 + 进行字符串连接,使用 * 进行字符串重复,使用 [] 或 [:] 进行字符串切片。例如:

a = "hello"
b = 'world'
print(a + " " + b)  # 输出 hello world
print(a * 3)        # 输出 hellohellohello
print(b[0])         # 输出 w
print(b[1:4])       # 输出 orl
列表类型

Python 中使用方括号表示列表类型。可以使用索引和切片操作,使用 append 等函数添加元素,使用 remove 等函数删除元素。例如:

a = [1, 2, 3]
b = ["one", "two", "three"]
print(a[0])          # 输出 1
print(a[1:3])        # 输出 [2, 3]
a.append(4)
print(a)             # 输出 [1, 2, 3, 4]
b.remove("two")
print(b)             # 输出 ["one", "three"]
字典类型

Python 中使用花括号表示字典类型,字典类型表示的是键值对的映射关系。可以使用键访问值,使用 items 等函数访问键值对。例如:

a = {"name": "Tom", "age": 18}
print(a["name"])            # 输出 Tom
print(a.get("height", 175)) # 输出 175
for key, value in a.items():
    print(key, value)       # 输出 name Tom 和 age 18
控制流语句
条件语句

Python 中使用 if, elif, else 关键字表示条件语句。例如:

a = 3
if a > 5:
    print("a is greater than 5")
elif a > 3:
    print("a is greater than 3 and less than or equal to 5")
else:
    print("a is less than or equal to 3")
循环语句

Python 中使用 for 和 while 关键字表示循环语句。for 循环可以遍历任何序列,如字符串、列表和字典。while 循环会一直执行,直到给定的条件成立或者使用 break 语句跳出循环。例如:

a = ["apple", "banana", "cherry"]
for x in a:
    print(x)

i = 0
while i < 3:
    print(i)
    i += 1
函数操作

Python 中使用 def 关键字定义函数。函数可以接受参数和返回值。例如:

def add(a, b):
    return a + b

print(add(2, 3))  # 输出 5
文件操作

Python 中使用 open 和 close 函数打开和关闭文件。可以使用 read 和 write 函数读取和写入文件。例如:

f = open("example.txt", "w")
f.write("This is an example.\n")
f.close()

f = open("example.txt", "r")
print(f.read())
f.close()

以上是 Python 中常用的一些操作,更多操作可以查看 Python 官方文档。