繁体   English   中英

为什么这个简单的滚模代码不能“打印”任何东西?

[英]Why doesn't this simple roll die code 'print' anything?

教科书上有这个示例代码逐字写入,但是当我按shift + enter时,没有output,我不知道为什么。

我尝试将 n = 10 放在括号中,并再次通过将值 10 分配给变量。

import random

def rollDie():
    return random.choice([1,2,3,4,5,6])

def rollN(n):
    result = ''
    for i in range(n):
         result = result + str(rollDie())
    print(result)

我没有收到任何类型的 output 或错误消息。 它说如果我运行 rollN(10),我应该得到 1-6 的 10 个随机整数,但我什么也得不到。

您没有调用 rollN() function。 尝试这个:

import random

def rollDie():
    return random.choice([1,2,3,4,5,6])

def rollN(n):
    result = ''
    for i in range(n):
         result = result + str(rollDie())
    print(result)

def main():
    rollN(10)

if __name__ == "__main__":
    main()

“我试过把 n = 10,”

这里的问题是您定义了两个函数,但它们从未被执行 因此,即使在 function 参数中设置 n = 10,function 仍然没有被实际调用。

尝试

import random
def rollDie(m):
    return random.choices(range(m))[0]

def rollN(n,m=6):
    print(" ".join(map(str,[rollDie(m) for i in range(n)])))

print(rollN(10))

此处代码的问题是您正在定义函数,但没有在任何地方调用它们。 尝试这个:

import random

def rollDie():
    return random.choice([1,2,3,4,5,6])

def rollN(n):
    result = ''
    for i in range(n):
         result = result + str(rollDie())
    print(result)

rollN(10)

如果您愿意,可以将代码缩短为:

import random

def rollN(n):
    result = ''
    for i in range(n):
        result = result + str(return random.choice([1,2,3,4,5,6]))
    print(result)

rollN(10)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM