python基础代码大全
python基础代码大全详细介绍
以下是一些Python基础代码示例:
一、变量和数据类型
1. 变量定义与基本数据类型
- # 整数
age = 20
# 浮点数
height = 1.75
# 字符串
name = "John"
# 布尔值
is_student = True
2. 数据类型转换
- # 整数转字符串
num_str = str(10)
# 字符串转整数
int_num = int("20")
# 浮点数转整数(截断小数部分)
int_from_float = int(3.14)
二、运算符
1. 算术运算符
- a = 5
b = 3
# 加法
sum_result = a + b
# 减法
diff_result = a - b
# 乘法
product_result = a * b
# 除法
quotient_result = a / b
# 取余
remainder_result = a % b
2. 比较运算符和逻辑运算符
- x = 10
y = 7
# 比较运算符
greater_than = x > y
less_than = x < y
equal_to = x == y
# 逻辑运算符
and_result = (x > 5) and (y < 10)
or_result = (x < 5) or (y > 5)
not_result = not (x == 10)
三、控制结构
1. 条件语句(if - elif - else)
- score = 80
if score >= 90:
print("优秀")
elif score >= 60:
print("合格")
else:
print("不合格")
2. 循环语句(for循环和while循环)
- for循环:
- fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
- while循环:
- count = 0
while count < 5:
print(count)
count += 1
四、函数
1. 定义和调用函数
- def add_numbers(a, b):
return a + b
result = add_numbers(3, 5)
print(result)
2. 函数参数默认值
- def greet(name="World"):
print("Hello, " + name + "!")
greet()
greet("Alice")
五、数据结构
1. 列表(List)
- # 创建列表
my_list = [1, 2, 3, 4, 5]
# 访问列表元素
print(my_list[0])
# 修改列表元素
my_list[1] = 10
# 列表切片
sub_list = my_list[1:3]
# 列表方法(添加元素)
my_list.append(6)
2. 元组(Tuple)
- # 创建元组(不可变)
my_tuple = (1, 2, 3)
# 访问元组元素
print(my_tuple[0])
3. 字典(Dict)
- # 创建字典
my_dict = {"name": "John", "age": 20}
# 访问字典元素
print(my_dict["name"])
# 修改字典元素
my_dict["age"] = 21
# 添加新元素
my_dict["city"] = "New York"
4. 集合(Set)
- # 创建集合
my_set = {1, 2, 3, 3} # 自动去重
# 添加元素
my_set.add(4)
# 集合运算
another_set = {3, 4, 5}
union_result = my_set | another_set
intersection_result = my_set & another_set