在Python中设置简单函数

2024-09-24 22:26:42 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试编写一个函数,它将我的输入作为骰子数量,获取骰子数量在1,6之间的随机数,然后将这些数字附加到一个列表中。你知道吗

我尝试了不同的返回消息,但我似乎无法将其附加到列表中,也无法真正思考我的代码还能做些什么。你知道吗

terninger = []
def terning_kast(antal_kast = int(input("Hvor mange terningekast? "))):
    for x in range(antal_kast, 0, -1):
        resultat = random.randint(1, 6)
        terninger.append(resultat)
    return resultat
print(terninger)

我希望代码将随机数1,6附加到上面的列表中(terninger),但我只收到一个空列表。你知道吗


Tags: 函数代码消息列表input数量def数字
2条回答

你的逻辑中有几点需要纠正。同时,以下可能是你想要的。你知道吗

import random as rnd

def terning_kast(count):
    terninger = []
    for x in range(count, 0, -1):
        resultat = rnd.randint(1, 6)
        terninger.append(resultat)
    return terninger

if __name__ == "__main__":
    cnt = input("Hvor mange terningekast? ")
    if cnt.isdigit():
        print(terning_kast(int(cnt)))
    else:
        print("Invalid entry")
  1. 为了使用随机模块,首先需要将其导入到模块中。你知道吗
  2. 尽管您将生成的随机数追加到列表中,但您从未尝试返回该列表。返回的是randint(x,y)函数调用的最后一个result实例。你知道吗
  3. 您正在将函数定义为模块/脚本的一部分。为了执行该函数,您必须在模块内调用它或将其导入其他模块。如果您查看我的示例,if__name__ == "__main__":指示python解释器运行您的脚本(如果您要从同一模块执行)。如果您要从其他模块使用这个模块(导入),那么您不需要提到这个if__name__ == "__main__":

您忘记调用函数=>;terning_kast()

terninger = []
def terning_kast(antal_kast = int(input("Hvor mange terningekast? "))):
    for x in range(antal_kast, 0, -1):
        resultat = random.randint(1, 6)
        terninger.append(resultat)
    return resultat

print('before', terninger)
terning_kast() # this is the line which you have missed
print('after', terninger)

相关问题 更多 >