为什么我的循环没有完成打印函数



我是python的新手,谁能解释一下为什么我的代码不工作,当我运行它时,它会打印出数字,即使它打印一个10,它也不会打印完成,请帮助

while True:
a = 10
from random import seed
from random import randint
seed(1)
for _ in range(10):
b = randint(0, 10)
print(b)
if b == a:
print('done')    

else:
continue

根据代码和给出的解释,我假设您希望上面的脚本随机生成一组数字,直到打印出10。一旦打印出10,您希望程序停止。

你需要这样做:

from random import seed
from random import randint
seed(1)
break_value = 10
b = 0
# The loop runs until b hits the designated break value (10)
while (b != break_value):
# Every loop a new b value is generated and output
b = randint(0, 10)
print(b)
# After the while loop terminates, we print done
print("done")

输出:

2
9
1
4
1
7
7
7
10
done

好吧,你只需要使用一个post条件while循环,所以当val =10时它中断。此外,print("done")应该在循环之外,以避免重复

import random as r #imported module
x = True 
stop_value = 10 #target value
while x:
val = r.randint(1,10)
print(val)
if val == stop_value:
x = False #this break the while loop when val = target value
print("done")

最新更新