正文
Python 循环语句(while, for)
小程序:扫一扫查出行
【扫一扫了解最新限行尾号】
复制小程序
【扫一扫了解最新限行尾号】
复制小程序
# while的使用
# 要注意些循环的时候,要考虑好循环的结束
# 考虑循环结束的方法有2种:
# 1.考虑在循环体里改变while 的条件
# 2.在循环体通过break 语句跳出循环 # 方法1的应用,在循环体改变while的条件
i = 0
while i < 5 :
print("1.hello world")
i += 1 # 方法2.在循环体通过break 语句跳出循环
i = 0
while True:
print("2.hello world")
i += 1
if i >= 5 :
break # while else使用,
i = 0
while i != 5:
print("3.hello world")
i += 1 #主要是在这里如果不是加1 ,就会出死循环
else:
print("打印完毕") #求1..10的和
sum = 0;
i = 1;
while i <=10:
sum += i
i += 1
else:
print("计算完毕和为:",sum) # for 循环的使用
# 主要用在遍历集合,如遍历字符串,列表等 notice = "你好,中国"
# name 可以任意合法的变量名字
for name in notice:
print(name) # for 循环也可以和else使用
# for 只要能顺利执行完,都会去执行else,break除外,while也要注意这个问题
pets = ["小黑","小黄","小白"]
for pet in pets:
print(pet)
else:
print("For循环完毕") # 利用for循环
# range 函数
for n in range(1,101):
if (n % 2 == 0):
print(n) # break 跳出这个循环体,结束整个循环
# continue 结束本次循环,继续执行下次循环
# pass 代表一个语句,其他程序没有这个实现 for num in range(1,11):
if num == 6:
break
print(num) for num in range(1,11):
if num == 6:
continue
print(num)