今天就跟大家聊聊有关Python有哪些循环判断语句,可能很多人都不太了解,为了让大家更加了解,小编给大家总结了以下内容,希望大家根据这篇文章可以有所收获。
一、if判断语句
1. if...else
if 条件:
满足条件时要做的事情1
满足条件时要做的事情2
......
else:
不满足条件时要做的事情1
不满足条件时要做的事情2
......
# -*- coding:utf-8 -*-
age = input("请输入年龄:")
age = int(age)
if age > 18:
print("已经成年")
else:
print("未成年")
2. elif
elif的使用格式如下:
if xxx1:
事情1
elif xxx2:
事情2
elif xxx3:
事情3
说明:
当xxx1满足时,执行事情1,然后整个if结束。
当xxx1不满足时,那么判断xxx2,如果xxx2满足,则执行事情2,然后整个if结束。
当xxx1不满足时,xxx2也不满足,如果xxx3满足,则执行事情3,然后整个if结束。
score = 66
if score>=90 and score<=100:
print('本次考试,等级为A')
elif score>=80 and score<90:
print('本次考试,等级为B')
elif score>=70 and score<80:
print('本次考试,等级为C')
elif score>=60 and score<70:
print('本次考试,等级为D')
elif score>=0 and score<60:
print('本次考试,等级为E')
3. if嵌套
if嵌套的格式
if 条件1:
满足条件1 做的事情
if 条件2:
满足条件2 做的事情
说明:
内外层都可以是if-else语句
内外层的判断标准是tab缩进
# -*- coding:utf-8 -*-
ticket = 0 #车票,非0代表有车票,0代表没有车票
suitcase = 1 #手提箱,0代表检查合格,非0代表有违禁品
if ticket != 0:
print("有车票,可以进站")
if suitcase == 0:
print("通过安检")
print("终于可以见到Ta了,美滋滋~~~")
二、while循环
1. while循环的格式
while 条件:
条件满足时,做的事情1
条件满足时,做的事情2
条件满足时,做的事情3
# 计算1~100里所有偶数的和<br>i = 1
sum = 0
while i<=100:
if i%2 == 0:
sum = sum + i
i+=1
print("1~100的累积和为:%d"%sum)
2. while嵌套
while 条件1:
条件1满足时,做的事情1
条件1满足时,做的事情2
while 条件2:
条件2满足时,做的事情1
条件2满足时,做的事情2
要求:打印如下图形:
* * * * * * * * * * * * * * *
i = 1
while i <= 5:
j = 1
while j <= i:
# print默认用/n作为结束符,这里不能换行,重新指定结束符end=''
print("* ", end='')
j += 1
# 这里使用默认的换行即可,不需要任何内容
print()
i += 1
3. while+else
与其它语言else 一般只与if 搭配不同,在Python 中还有个while ...else 语句,while 后面的else 作用是指,当while 循环正常执行完,中间没有被break 中止的话,就会执行else后面的语句。
count = 0
while count <= 5 :
count += 1
print("Loop",count)
else:
print("循环正常执行完啦")
print("-----out of while loop ------")
输出
Loop 1
Loop 2
Loop 3
Loop 4
Loop 5
Loop 6
循环正常执行完啦
-----out of while loop ------
#如果执行过程中被break啦,就不会执行else的语句啦
count = 0
while count <= 5 :
count += 1
if count == 3:break
print("Loop",count)
else:
print("循环正常执行完啦")
print("-----out of while loop ------")
输出
Loop 1
Loop 2
-----out of while loop ------
三、for循环
for 临时变量 in 列表或者字符串等:
循环满足条件时执行的代码
else:# 选择性使用
循环不满足条件时执行的代码
# 打印九九乘法表
for i in range(1, 10):
for j in range(1, i + 1):
print('%s*%s=%s' % (j, i, i * j), end=' ')
print()
四、break和continue
#break用于退出本层循环
while True:
print "123"
break
print "456"
#continue用于退出本次循环,继续下一次循环
while True:
print "123"
continue
print "456"
看完上述内容,你们对Python有哪些循环判断语句有进一步的了解吗?如果还想了解更多知识或者相关内容,请关注亿速云行业资讯频道,感谢大家的支持。
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。