三小时快速入门Python第三篇--控制流分支与循环

控制流分支与循环

1、分支结构

注意:Python 中没有 switch/case 语法

复制代码
 1 # 先定义一个变量
 2 some_var = 5
 3 # 这里用到了if语句 缩进是Python里的重要属性
 4 # 打印 "some_var is smaller than 10"
 5 if some_var > 10:
 6     print ("some_var is totally bigger than 10.")
 7 elif some_var < 10:    # This elif clause is optional.
 8     print ("some_var is smaller than 10.")
 9 else:           # This is optional too.
10     print ("some_var is indeed 10.")
复制代码

2、循环结构

复制代码
# For 循环用来遍历一个列表
for animal in ["dog", "cat", "mouse"]:
    # 使用{0}格式 插入字符串
    print ("{0} is a mammal".format(animal))

# "range(number)" 返回一个包含数字的列表
for i in range(4):
    print (i)

# "range(lower, upper)" 返回一个从lower数值到upper数值的列表
for i in range(4, 8):
    print (i)

# "range(lower, upper, step)" 返回一个从lower数值到upper步长为step数值的列表
# step 的默认值为1
for i in range(4, 8, 2):
    print(i)

# While 循环会一致执行下去,直到条件不满足
x=0
while x < 4:
    print(x)
    x+=1 #x=x+1的简写
复制代码

 上一篇:三小时快速入门Python第二篇--变量与集合

 下一篇:三小时快速入门Python第四篇--函数与对象

posted @   小尾学长  阅读(822)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
阅读排行:
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 零经验选手,Compose 一天开发一款小游戏!
· 通过 API 将Deepseek响应流式内容输出到前端
· 因为Apifox不支持离线,我果断选择了Apipost!
点击右上角即可分享
微信分享提示