【Python快速入门和实践004】Python控制流

4. 控制流

        控制流是程序执行顺序的控制方式,包括条件语句和循环语句。通过控制流,我们可以在程序中实现各种逻辑判断和重复操作。

   4.1 条件语句

条件语句用于根据条件的真值来决定是否执行某段代码。

     4.1.1 if 语句

if 语句用于在条件为真时执行某段代码。

x = 10

if x > 5:
    print("x is greater than 5")  # 输出: x is greater than 5

     4.1.2 if-else 语句

if-else 语句用于在条件为真时执行一段代码,否则执行另一段代码。

x = 3

if x > 5:
    print("x is greater than 5")
else:
    print("x is less than or equal to 5")  # 输出: x is less than or equal to 5

     4.1.3 if-elif-else 语句

if-elif-else 语句用于根据多个条件执行不同的代码段。

x = 5

if x > 5:
    print("x is greater than 5")
elif x == 5:
    print("x is equal to 5")  # 输出: x is equal to 5
else:
    print("x is less than 5")

   4.2 循环语句

循环语句用于重复执行一段代码,直到某个条件不再满足。

     4.2.1 for 循环

for 循环用于遍历序列(如列表、元组、字典、集合等)中的每一个元素。

# 遍历一个列表
numbers = [1, 2, 3, 4, 5]

for num in numbers:
    print(num)
# 输出:
# 1
# 2
# 3
# 4
# 5

     4.2.2 while 循环

while 循环在条件为真时反复执行某段代码。

x = 0

while x < 5:
    print(x)
    x += 1
# 输出:
# 0
# 1
# 2
# 3
# 4

     4.2.3 循环中的 `break` 和 `continue`

  • break 用于提前终止循环。
  • continue 用于跳过当前迭代,继续下一次循环。
# 使用 break 提前终止循环
for num in range(10):
    if num == 5:
        break
    print(num)
# 输出:
# 0
# 1
# 2
# 3
# 4

# 使用 continue 跳过特定条件
for num in range(10):
    if num % 2 == 0:
        continue
    print(num)
# 输出:
# 1
# 3
# 5
# 7
# 9

   4.3 列表、字典、集合的遍历

不同的数据结构有不同的遍历方式。

遍历列表:

# 使用 for 循环遍历列表
numbers = [1, 2, 3, 4, 5]

for num in numbers:
    print(num)
# 输出:
# 1
# 2
# 3
# 4
# 5

遍历字典:

# 使用 for 循环遍历字典的键和值
person = {"name": "Alice", "age": 30, "city": "New York"}

# 遍历键
for key in person:
    print(key, person[key])
# 输出:
# name Alice
# age 30
# city New York

# 或者使用 items() 遍历键值对
for key, value in person.items():
    print(key, value)
# 输出:
# name Alice
# age 30
# city New York

遍历集合:

# 使用 for 循环遍历集合
fruits = {"apple", "banana", "cherry"}

for fruit in fruits:
    print(fruit)
# 输出顺序是无序的,可能不同:
# apple
# banana
# cherry

  • 3
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值