我目前正在为我必须接受用户的数字列表的课程进行分配,然后获取该列表,查找数字的总和(否那里的问题),最后在该列表中找到每个单独价值的平方。我在开发称为" SquareEarch"的功能方面遇到麻烦。我尝试了一些想法,但在调用功能或错误时,它最终在我的打印行中打印了" none "。我觉得我可能会缺少一些东西,如果有人可以将我指向正确的方向,以开发如何在输入列表中与每个值保持平衡,我将非常感谢!
如果我需要更多地了解我的问题,我会这样做。代码的示例以及我要放置代码的哪些/要放置的示例。这是我的第一篇文章,所以很抱歉,如果布局有点草率。
#function "squareEach" here
def sumList(nums):
total=0
for n in nums:
total=total+n
return total
def main():
print("This program finds the sum of a list of numbers and finds the")
print("square of each number in the list.n")
nums=map(int,input("Enter the numbers separated by a space: ").split())
print("The sum is", sumList(nums))
#Line that prints what the squares are for each value e.g("The squares
for each value are... ")
main()
问题是您使用<map>
对象类型。nums
变量是对象类型class <map>
。不幸的是,对象/类的内容将在您的第一个函数中,在for
中的第一个功能中会更改。然后,用户必须将新数字重新输入到nums
变量中。即使不使用math
模块,计算平方根的功能也很简单,也就是说: n**(1/2.0)
def squareEach(numbers):
result = {}
for n in numbers:
result[n] = n ** (1 / 2.0)
return result
# result is dictionary data type, but you can change the function, if you need another data type as the result
def sumList(numbers):
total = 0
for n in numbers:
total += n
return total
nums = list(map(int, input("Enter the numbers separated by space: ").split()))
# nums variable is the <list> type variable with a <int> entries
print("The sum is", sumList(nums))
print("The suqare for each is", squareEach(nums))