【Python 笔记(二)——基本语句 变量类型 字符串 序列 列表与元组 字典与集合】

基本语句

在 Python 中,基本语句可以帮助我们完成一些基本的操作,如控制流程、定义函数等。以下是 Python 中的几种基本语句:

if 语句

if 语句用于判断某个条件是否成立,如果条件成立则执行相应的代码块。

num = 6
if num > 5:
    print("num > 5")
else:
    print("num <= 5")

for 语句

for 语句用于遍历序列中的元素,依次执行相应的代码块。

list = ["apple", "banana", "cherry"]
for item in list:
    print(item)

while 语句

while 语句用于执行某个代码块,直到指定的条件不满足为止。

i = 1
sum = 0
while i <= 10:
    sum += i
    i += 1
print(sum)

break 语句

break 语句用于跳出当前循环。

for i in range(1, 11):
    if i == 5:
        break
    print(i)

continue 语句

continue 语句用于跳过当前循环中的某个元素。

for i in range(1, 11):
    if i == 5:
        continue
    print(i)

变量类型

在 Python 中,数字是一种基本数据类型,包括整数、浮点数和复数。Python 中的数字类型支持基本的算术运算和逻辑运算。

整数

a = 10
b = 4
print(a + b)  # 加
print(a - b)  # 减
print(a * b)  # 乘
print(a / b)  # 除

浮点数

c = 3.1415926
d = 2.71828
print(c + d)  # 加
print(c - d)  # 减
print(c * d)  # 乘
print(c / d)  # 除

复数

e = 2 + 3j
f = 4 + 5j
print(e + f)  # 加
print(e - f)  # 减
print(e * f)  # 乘
print(e / f)  # 除

字符串

在 Python 中,字符串是一种基本数据类型,表示文本内容。Python 中的字符串支持基本的操作,如切片、拼接、格式化等。

字符串切片

str = "Hello, world!"
print(str[0:5])  # 切片

字符串拼接

str1 = "Hello"
str2 = "world"
str3 = str1 + " " + str2
print(str3)

字符串格式化

name = "Bob"
age = 25
print("My name is %s, and I am %d years old." % (name, age))

序列

在 Python 中,序列是指由一组有序的元素构成的数据类型,包括列表、元组和字符串。Python 中的序列支持基本的操作,如索引、切片、拼接、重复等。

列表操作

list = ["apple", "banana", "cherry"]
print(list[0])  # 索引
print(list[1:3])  # 切片
list2 = ["orange", "grape"]
list3 = list + list2  # 拼接
list4 = list * 2  # 重复

元组操作

tuple = ("apple", "banana", "cherry")
print(tuple[0])  # 索引
print(tuple[1:3])  # 切片

字符串操作

str = "Hello, world!"
print(str[0])  # 索引
print(str[0:5])  # 切片
str2 = "Python"
print(str + str2)  # 拼接
print(str * 2)  # 重复

列表与元组

在 Python 中,列表和元组是两种常见的序列类型,都可以用来存储一组有序的数据。虽然它们有很多相似的地方,但也有不同之处。

列表

列表是可变的,可以修改其中的元素;列表使用方括号[]来表示,元素之间使用逗号分隔。

list1 = ["apple", "banana", "cherry"]
list1.append("orange")  # 添加元素
list1.pop(1)  # 删除元素
list1[2] = "grape"  # 修改元素
print(list1)

元组

元组是不可变的,一旦创建就无法修改其中的元素;元组使用圆括号()来表示,元素之间也使用逗号分隔。

tuple1 = ("apple", "banana", "cherry")
print(tuple1[0])  # 访问元素
len(tuple1)  # 获取长度
tuple2 = tuple(list1)  # 列表转元组
print(tuple2)

字典与集合

在 Python 中,字典和集合是两种常见的非序列类型。字典用于存储键-值对,集合用于存储一组无序的唯一元素。

字典

字典使用花括号{}来表示,每个键值对之间使用冒号:分隔,键和值之间使用逗号,分隔。

dict1 = {
    
    "apple": 1, "banana": 2, "cherry": 3}
print(dict1["apple"])  # 访问元素
dict1["banana"] = 4  # 修改元素
dict1["orange"] = 5  # 添加元素
del dict1["cherry"]  # 删除元素
print(dict1)

集合

集合使用花括号{}来表示,元素之间使用逗号,分隔。

set1 = {
    
    1, 2, 3}
set2 = {
    
    2, 3, 4}
print(set1.union(set2))  # 并集
print(set1.intersection(set2))  # 交集
print(set1.difference(set2))  # 差集
set1.add(4)  # 添加元素
set1.remove(2)  # 删除元素
print(set1)

猜你喜欢

转载自blog.csdn.net/muzillll/article/details/130948202
今日推荐