获取python中函数的和
我的代码:获取python中函数的和,python,function,sum,Python,Function,Sum,我的代码: # -*- coding: utf-8 -*- def dice(): import random number = random.randint(1,6) print "The dice shows:" + str(number) [dice() for _ in range(3)] The dice shows:2 The dice shows:4 The dice shows:3 示例结果: # -*- coding: utf-8 -*- def
# -*- coding: utf-8 -*-
def dice():
import random
number = random.randint(1,6)
print "The dice shows:" + str(number)
[dice() for _ in range(3)]
The dice shows:2
The dice shows:4
The dice shows:3
示例结果:
# -*- coding: utf-8 -*-
def dice():
import random
number = random.randint(1,6)
print "The dice shows:" + str(number)
[dice() for _ in range(3)]
The dice shows:2
The dice shows:4
The dice shows:3
如果我想对列表中的所有数字求和,我该怎么做?(在这种情况下,我将得到总数9)对于手动计算:
import random
def dice():
return random.randint(1,6)
list = []
for i in range(3):
list.append(dice())
sum = 0
for i in list:
sum +=i
print sum
内置式suming:
print sum([dic() for _ in range(3))
嗯,我认为您应该多读一点Python,因为您甚至在逻辑之前就有一些疑问 这是我认为你应该做的
import random
def dice():
return random.randint(1,6)
sum([dice() for i in range(3)])
您的函数正在将结果打印为字符串,而不是返回结果。使用
sum()
。(并且不要在函数中导入随机)感谢链接和答案,这是我试用Python的第一天。有趣,但很难!:)