循环语句

Posted zyg-ayy

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了循环语句相关的知识,希望对你有一定的参考价值。

# 1.循环打印"人生苦短,及时行乐。"
while True:
print(‘人生苦短,及时行乐‘)

# 2.while后加入条件
while 1 > 0:
print(‘人生苦短,不如去死‘)

# 3.数字相加
count = 1
count = count + 1
print(count)

# 4.通过循环,让count每次循环都+1
count = 1
while True:
print(count)
count = count + 1 # 将变量count重新赋值之后再输出

# 5.通过循环,打印1,2,3....10
count = 1
while count <= 10:
print(count)
count = count + 1

# 6.通过循环,打印1,2,3,4,5,6,8,9,10
# ①先打印1到6,再打印8到10
count = 1
while count <= 6:
print(count)
count = count + 1
count = 8
while count <= 10:
print(count)
count = count + 1

# ②在while中嵌套一个if实现
count = 1
while count <= 10:
if count != 7:
print(count)
count = count + 1

# ③.引入pass
count = 1
while count <= 10:
if count == 7:
pass # 当执行到count = 7时,直接跳过
else:
print(count)
count = count + 1 # 变量count是在while的下一级

# 7.关键字break
while True:
print(666)
break # 注:终止当前循环
print(‘结束‘)

# 练习1:通过break实现1~10
count = 1
while True:
print(count)
count = count + 1
if count == 11:
break
print(‘结束‘)

# break始终终止当前循环
while True:
print(‘你好!‘)
while True:
print(666)
break
break

# 关键字continue
count = 1
while True:
print(count)
continue # 本次循环不再继续往下走,回到while条件位置
count = count + 1
# 练习1~10,不打印7
count = 1
while count <= 10:
if count == 7:
count = count + 1
continue
print(count)
count = count + 1

# 9.while else
count = 1
while count <= 10:
print(count)
count = count + 1
else: # 不再满足while条件或条件=False时执行此步骤
print(‘ELSE代码块‘)

以上是关于循环语句的主要内容,如果未能解决你的问题,请参考以下文章

JavaScript的循环语句

Verilog循环语句

Python--循环语句

Go 循环语句

C语言分支语句与循环语句

shell编程之case分支语句,for循环语句和while循环语句