Python 如何用随机数构造函数

Python 如何用随机数构造函数,python,function,random,iteration,Python,Function,Random,Iteration,嗨,我正在尝试创建一个函数,将选择5个随机数,这将等于一个总数已经给定,并把5个数字在一个列表中。当我通过函数传递一个数字时,我得到一个错误。 我似乎不明白我做错了什么 def num_lottery(total_num): the_set =[] n1 = random.randint(1, total_num) n2 = random.randint(1, total_num - n1) n4 = random.randint(1, total_num - (

嗨,我正在尝试创建一个函数,将选择5个随机数,这将等于一个总数已经给定,并把5个数字在一个列表中。当我通过函数传递一个数字时,我得到一个错误。 我似乎不明白我做错了什么

def num_lottery(total_num):
    the_set =[]
    n1 = random.randint(1, total_num)
    n2 = random.randint(1, total_num - n1)
    n4 = random.randint(1, total_num - (n1 + n2 + n3))
    n5 = total_num - (n1 + n2 + n3 + n4)
    the_set.append(n1, n2, n3, n4, n5)
    return the_set
当我通过total_num=50000时,它起作用,但当total_num=5000时不起作用。 感谢您的帮助。
谢谢

我现在不了解python编码,但看看代码中的变量n3:

def num_lottery(total_num):
    the_set =[]
    n1 = random.randint(1, total_num)
    n2 = random.randint(1, total_num - n1)
    n4 = random.randint(1, total_num - (n1 + n2 + **n3**))
    n5 = total_num - (n1 + n2 + n3 + n4)
    the_set.append(n1, n2, n3, n4, n5)
    return the_set
它没有在任何地方定义。
我想你的意思是:

def num_lottery(total_num):
    the_set =[]
    n1 = random.randint(1, total_num)
    n2 = random.randint(1, total_num - n1)
    **n3 = random.randint(1, total_num - (n1+n2)**
    n4 = random.randint(1, total_num - (n1 + n2 + **n3**))
    n5 = total_num - (n1 + n2 + n3 + n4)
    the_set.append(n1, n2, n3, n4, n5)
    return the_set

我希望这能起作用。

似乎您错过了
n3
初始化。添加n3初始化后,此代码对我有效。
我收到一个错误。
-这是什么意思
但当total_num=5000时不是这样-您希望得到什么结果?当发布有关产生异常的代码的问题时,始终包括完整的回溯-复制并粘贴它,然后将其格式化为代码(选择它并键入
ctrl-k
)。。。