python - Finding the squares of each number in a user input list. (Python 3.x)
问题描述
I'm currently working on an assignment for a course where I have to accept a list of numbers from a user, and then take that list, find the sum of the numbers combined (no issues there), and finally find the squares of each individual value in that list. I am having trouble with developing the function I'm calling "squareEach". I have tried a few ideas but it has ended up printing "none" in my print line when calling the function or an error. I feel I may be missing something and if someone could point me in the right direction for how to develop a function to square each value in an input list, I'd really appreciate it!
If I need to clear a bit more up about my problem I'll do so. A sample of the code and what/where I want to put code is below. This is my first post so I'm sorry if the layout is a bit sloppy.
#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))
推荐阅读
- javascript - 如何在地图函数中调用api
- python - F字符串自动完成python
- azure-devops - 如何从 Azure DevOps 访问 pagesBatch?
- angularjs - 有什么方法可以减少 AngularJS 包的大小(使用 Webpack)
- android - 未找到改造响应
- javascript - 如何避免呈现复选框编号?
- agda - 立方体agda中具有不同refl组合的立方体
- wpf - WPF 是否有任何方法可以将徽章应用于应用程序图标?
- python - 第一次显示输出后,如何让该程序无限次地再次输入输入?
- rust - 为什么 std::rc::Rc 可以调用自己的值的方法?