我对python还不熟悉,只是处于基础知识的初级阶段。有人能解释一下下面代码中的for循环是如何工作的吗?我真的不明白数字9是如何得到3作为内在价值的。
请告诉我循环是如何执行的。蒂娅。
代码:
for outer in range(2,10):
for inner in range(2,outer):
if not outer%inner:
print(outer,'=',inner,'*',int(outer/inner))
break
else:
print(outer,'is prime')Output:
2 is prime
3 is prime
4 = 2 * 2
5 is prime
6 = 2 * 3
7 is prime
8 = 2 * 4
9 = 3 * 3发布于 2020-01-03 18:53:15
内循环对外部循环的每次执行运行多次。
对于外部循环的值9,内环执行从2到外部值。
发布于 2020-01-03 18:55:42
我在下面对您的代码进行了注释,它应该解释正在发生的事情。
# This loop loops through numbers 2-9, and assigns them to the variable 'outer'
for outer in range(2,10):
# This loop loops through numbers 2-(outer-1), and assigns them to the variable 'inner'
for inner in range(2,outer):
# if outer % inner == 0, the code is executed
if not outer%inner:
# When this is executed for 9, it will print 9 = 3 * 3
print(outer,'=',inner,'*',int(outer/inner))
break
else:
print(outer,'is prime')发布于 2020-01-03 18:51:12
对于外部循环的每一次执行,您的内环执行多次。
对于外部值9,内部循环将从2执行到(外部),即9。
https://stackoverflow.com/questions/59583776
复制相似问题