python——循环


1、逻辑判断

在计算机中,针对不同情况,使用逻辑判断的方式,逻辑判断使用的关键字是:if——elif(else if)——else,如针对学生成绩判断等级,具体如下:

studentScore=int(input("请输入学生成绩\n"))
if studentScore>=0 and studentScore<60:
   print("继续努力")
elif studentScore>=60 and studentScore<80:
   print("还可以更进一步")
elif studentScore>=80 and studentScore<=90:
   print("优秀,但还有进步空间")
elif studentScore>90 and studentScore<=100:
   print("非常棒,继续努力")
else:
   print("不成立")

2、循环语句

2.1for循环

for循环的代码为:for 变量(自定义) in 想要循环的变量,获取到被循环对象的索引信息:enumerate。

(1)for循环

#for循环
yl="1234567"
for math in yl:
	print(math)

(2)获取被循环对象的内容和其对应的索引信息:enumerate

#enumerate:获取到被循环对象的索引信息
qy="我有一只cat叫做团子!"
for yz in enumerate(qy):
	print(yz)

(3)验证对象某个索引对应的内容

#验证对象某个索引对应的内容
qy="我有一只cat叫做团子!"
for index,yz in enumerate(qy):
	if index == 4 and yz == "c":
		print('ok')

2.2while循环

while循环的关键字是:while True,他是一个死循环。跳出循环的关键字是:break。继续执行循环的关键字是:continue。也可以在for循环中使用,但是需要结合逻

辑判断使用。

(1)无限循环

#无限循环
while True:
	studentScore=int(input("请输入学生成绩\n"))
	if studentScore>=0 and studentScore<60:
		print("继续努力")
	elif studentScore>=60 and studentScore<80:
		print("还可以更进一步")
	elif studentScore>=80 and studentScore<=90:
		print("优秀,但还有进步空间")
	elif studentScore>90 and studentScore<=100:
		print("非常棒,继续努力")

(2)结束循环和继续循环

#遇到0-100的数字以及数字120程序继续执行,遇到数字150和其他结束执行。
while True:
	studentScore=int(input("请输入学生成绩\n"))
	if studentScore>=0 and studentScore<60:
		print("继续努力")
	elif studentScore>=60 and studentScore<80:
		print("还可以更进一步")
	elif studentScore>=80 and studentScore<=90:
		print("优秀,但还有进步空间")
	elif studentScore>90 and studentScore<=100:
		print("非常棒,继续努力")
	elif studentScore==120:continue
	elif studentScore == 150:break
	else:
		break