百度
360搜索
搜狗搜索

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

阅读更多 >>>  typedef和define的区别与用法,C语言type 与 #define 定义区别
← 上一篇: 下一篇:

网站数据信息

"python基础代码大全"浏览人数已经达到21次,如你需要查询该站的相关权重信息,可以点击进入"Chinaz数据" 查询。更多网站价值评估因素如:python基础代码大全的访问速度、搜索引擎收录以及索引量、用户体验等。 要评估一个站的价值,最主要还是需要根据您自身的需求,如网站IP、PV、跳出率等!