速查Python课后第011讲:求阶梯数flag = 1 与 break 作用一样吧
本帖最后由 小蜂队 于 2021-11-24 17:33 编辑0.x = 7
i = 1
flag = 0
while i <= 100:
if (x%2 == 1) and (x%3 == 2) and (x%5 == 4) and (x%6==5):
flag = 1
else:
x = 7 * (i+1) # 根据题意,x一定是7的整数倍,所以每次乘以7
i += 1
if flag == 1:
print('阶梯数是:', x)
else:
print('在程序限定的范围内找不到答案!')
0.1执行程序后的结果截图:
1.使用 break语句后:
x = 7
i = 1
while i <= 100:
if (x%2 == 1) and (x%3 == 2) and (x%5 == 4) and (x%6==5):
print('阶梯数是:', x)
break
else:
x = 7 * (i+1) # 根据题意,x一定是7的整数倍,所以每次乘以7
i += 1
else:
print('在程序限定的范围内找不到答案!')
1.1 运行结果如图:
就我可以理解为 flag的作用便如同 break 一样满足条件时就终止了循环。 x = 7; i = 1
while not ((x%2 == 1) and (x%3 == 2) and (x%5 == 4) and (x%6==5)):
x = 7 * (i+1)
i += 1
else:
print('在程序限定的范围内找不到答案!')
print(f'阶梯数是:{x}')在程序限定的范围内找不到答案!
阶梯数是:119
页:
[1]