首页 > 解决方案 > 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()

标签: pythonmathuser-input

解决方案


问题是您使用<map>对象类型。nums变量是对象class <map>类型。不幸的是,对象/类的内容会在它的使用中发生变化,在你的第一个函数中,在循环中fornums然后,用户必须在变量中重新输入一个新数字。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))

推荐阅读