Python控制流程语句总结

'''
1.if判断语句

1.1单分支语句

if 表达式:
代码块

user = input("用户名>>")
pwd = input("密码>>")
if user == "root" and pwd == "123": # 返回一个布尔值
print("登录成功") # 强烈建议使用四个缩进

print("程序结束")

1.2双分支语句

if 表达式:
代码块 1
else:
代码块 2

user = input("用户名>>")
pwd = input("密码>>")

if user == "root" and pwd == "123": # 返回一个布尔值
print("登录成功") # 强烈建议使用四个缩进
print("祝贺你")
else:
print("登录失败")
print("不好意思")

1.3多分支语句

if 表达式 1:
代码块 1
elif 表达式 2:
代码块 2
elif 表达式 3:
代码块 3
...# 其它elif语句
else:
代码块 n

score = input("请输入您的成绩>>") # "100"
# 当成绩大于90的时候显示优秀,否则显示一般
# 将数字字符串,比如"100",转换成一个整型数字的时候,需要int转换
score = int(score) # 100

if score > 100 or score < 0:
print("您的输入有误!")
elif score > 90:
print("成绩优秀")
elif score > 70: # else if
print("成绩良好")
elif score > 60:
print("成绩及格")
else:
print("成绩不及格")

1.4if嵌套

score = input("请输入您的成绩>>") # "100"

if score.isdigit():
score = int(score) # 100
if score > 100 or score < 0:
print("您的输入有误!")
elif score > 90:
print("成绩优秀")
elif score > 70: # else if
print("成绩良好")
elif score > 60:
print("成绩及格")
else:
print("成绩不及格")
else:
print("请输入一个数字")
==============================

2.while循环语句

while 表达式:
循环体

2.1无限循环

# 案例1
while 1:
print("OK") # 无限循环打印OK,这样使用没有什么意义

# 案例2
while 1:

score = input("请输入您的成绩>>") # "100"

if score.isdigit():
score = int(score) # 100
if score > 100 or score < 0:
print("您的输入有误!")
elif score > 90:
print("成绩优秀")
elif score > 70: # else if
print("成绩良好")
elif score > 60:
print("成绩及格")
else:
print("成绩不及格")
else:
print("请输入一个数字")

2.2限定次数循环

循环打印十遍"hello world”

count = 0 # 初始化语句
while count < 10: # 条件判断
print("hello world")
count+=1 # 步进语句
print("end")
==============================

3.for循环语句

for 迭代变量 in 字符串|列表|元组|字典|集合:
代码块

for i in "hello world":
print(i)

for name in ["张三",'李四',"王五"]:
print(name)

for i in range(10): # [1,2,3,4,5,6,7,8,9] range函数: range(start,end,step)
print(i)
==============================

4.循环嵌套
在一个循环体语句中又包含另一个循环语句,称为循环嵌套

4.1独立嵌套

在控制台上打印一个如下图所示的正方形

*****
*****
*****
*****
*****

代码:
for i in range(5):
for j in range(5):
print("*",end="")
print("")

4.2关联嵌套

在控制台上打印一个如下图所示的三角形

*
**
***
****
*****

代码:
for i in range(5):
for j in range(i+1):
print("*",end="")
print("")
==============================
5.退出循环

如果想提前结束循环(在不满足结束条件的情况下结束循环),可以使用break或continue关键字。

break
当 break 关键字用于 for 循环时,会终止循环而执行整个循环语句后面的代码。break 关键字通常和 if 语句一起使用,即满足某个条件时便跳出循环,继续执行循环语句下面的代码。

continue
不同于break退出整个循环,continue指的是退出当次循环。
==============================
'''
posted @ 2022-03-24 20:54  呼长喜  阅读(70)  评论(0编辑  收藏  举报