【发布时间】:2021-02-26 22:19:07
【问题描述】:
我想做以下任务:
给定一个数字 N,假设它是 5。我想生成一个列表,其中包含从 1 到 N (5) 范围内的所有数字,并且不以随机顺序重复。
所以我写了这段代码。使用这些调试输出,我意识到循环几乎是无限的,即使它不应该是。
import random
def generate(n):
amount = n
print('Line 1 success') #TODO:DEBUG
randnum = 0
print('Line 2 success') #TODO:DEBUG
finished = False
print('Line 3 success') #TODO:DEBUG
nums = []
print('Line 4 success') #TODO:DEBUG
while amount != 0:
while finished != True:
print('Line 5 success', amount) #TODO:DEBUG
randnum = random.randint(1,n)
print('Line 6 success') #TODO:DEBUG
if not randnum in nums:
finished = True
nums.append(randnum)
print('Generation', amount, 'success') #TODO:DEBUG
print(nums, ' ; ', randnum) #TODO:DEBUG
print('Line 7 success') #TODO:DEBUG
amount = amount - 1
print('Line 8 success') #TODO:DEBUG
finished = False
print('Line 9 success') #TODO:DEBUG
print(nums)
generate(5)
它给了我一个无限循环,我不知道为什么以及如何解决它。
为什么是无限循环?
【问题讨论】:
-
问题是什么?
-
看起来你有一个无限循环。?如果您正在使用 IDE,现在是学习其调试功能的好时机 - 例如逐步执行、设置断点和检查值。或者你可以花点时间熟悉一下内置的Python debugger。
-
我在
nums.append之后添加了print(f'found another {nums}')并得到了...Generation -4 success found another [4, 5, 3, 1, 2]...,这样正在工作。 -
那么问题是什么?
-
今后,当您得到代码中众多问题的答案时,请不要修改您的问题。一问一答。这不是一个讨论论坛。我对使用 IDE 的调试功能或学习
pdb模块的评论是建设性的,从长远来看会对你有所帮助。
标签: python list random append generator