{site_name}

{site_name}

🌜 搜索

Python复合语句是包含多个单独语句的代码块,这些语句被组合在一起并形成一个逻辑单元

Python 𝄐 0
python复合语句,python复合语句用缩进表达层次关系,python复合语句怎么写,python复合类型,python复合数据类型有哪些,python中的复合运算
Python复合语句是包含多个单独语句的代码块,这些语句被组合在一起并形成一个逻辑单元。Python中有几种类型的复合语句,最常见的有条件语句(if/elif/else)、循环语句(for/while)、函数定义语句和类定义语句。

下面是一些Python复合语句的示例:

1. 条件语句

x = 5
if x > 10:
print("x is greater than 10")
elif x > 0:
print("x is between 0 and 10")
else:
print("x is negative")


2. 循环语句

# for循环
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)

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


3. 函数定义语句

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

result = add(3, 4)
print(result) # 输出7


4. 类定义语句

class Person:
def __init__(self, name, age):
self.name = name
self.age = age

def say_hello(self):
print("Hello, my name is " + self.name)

person1 = Person("Alice", 25)
person1.say_hello() # 输出 "Hello, my name is Alice"