Search code examples
pythonlistmedian

How to add the Numbers from the User into a List


I have been trying to write a Mean, Median, and Mode Calculator. I have two questions. 1) How would I add the numbers the user inputs into the empty list. If I simply punch in the numbers it gives me this error:

userNumbers = int(raw_input("Enter the digits here: "))
ValueError: invalid literal for int() with base 10: '2, 4, 6, 8'

I would love to know how to avoid that. Secondly, I am using Python 2.7.10 and will be moving to 3.4 soon. I know that on 3.4 there is a module named statistics with a median function, however it doesn't work on 2.7.10. Out of curiosity, how would I find the median without the function. Thanks everyone!

from collections import Counter


def numberPlacement():
    print("Welcome to the PyCalculator, please enter a series of digits!")
    userNumbers = int(raw_input("Enter the digits here: "))
    userNumbers = []


def userChoice():
    while True:
        print("Awesome, now that we haave your numbers please choose an operation (Mean, Median, or Mode!)")
        userAnswer = raw_input("Enter your choice here: ")
        if userAnswer == "Mean":
            mean = sum(userNumbers) / float(len(userNumbers))
            return mean
        elif userAnswer == "Mode":
            mode = Counter(userNumbers)
            return mode
        continue

print numberPlacement()
print userChoice()

Solution

  • The error you are receiving is because you are trying to cast invalid characters to int.

    Your input is: 1, 2, 3, 4 so those commas is what is causing that error.

    To rectify this, simply remove the int() cast you have, make your input a list by appending a .split(',') to your input. What that split does is convert your string to a list by splitting on the comma. That way you will have a list of numbers represented by strings.

    So, since you are doing math, you need to make sure you are actually using the numerical representation and not the string representation of the data in your list. There is a neat one line solution for this you can do, by using Python's map method (documentation), that will cast all your entries to an int.

    So, your user input, can simply look like this:

    Python 3:

    userNumbers = list(map(int, input("Enter the digits here: ").split(',')))
    

    Python 2:

    userNumbers = map(int, raw_input("Enter the digits here: ").split(','))
    

    There is another problem in your code. In your userChoice method, you are referencing userNumbers. Which I think is the reference to userNumbers inside the numberPlacement method. You can't do this.

    What I suggest doing, since it seems like you want to call these two methods separately, is make your userChoice method take a parameter, which would be a list, called userNumber. So simply:

    def userChoice(userNumbers):
        # the rest of your code
    

    Now, it is very important to remember, that this userNumbers in your userChoice method is not the same as the userNumbers in your numberPlacement method. To understand why, this is part of scoping. Which you can read about here.

    So, then when you call your methods now, you just have to do something like this:

    number_placements = numberPlacement()
    print(number_placements)
    print(userChoice(number_placements))
    

    When you put it all together, your code now looks like this:

    (Python 2)

    from collections import Counter
    
    
    def numberPlacement():
        print("Welcome to the PyCalculator, please enter a series of digits!")
        userNumbers = map(int, raw_input("Enter the digits here: ").split(','))
        return userNumbers
    
    
    def userChoice(userNumbers):
        while True:
            print("Awesome, now that we haave your numbers please choose an operation (Mean, Median, or Mode!)")
            userAnswer = raw_input("Enter your choice here: ")
            if userAnswer == "Mean":
                mean = sum(userNumbers) / float(len(userNumbers))
                return mean
            elif userAnswer == "Mode":
                mode = Counter(userNumbers)
                return mode
            continue
    
    
    r = numberPlacement()
    print(userChoice(r))
    

    Demo:

    Welcome to the PyCalculator, please enter a series of digits!
    Enter the digits here: 1,2,3,4
    Awesome, now that we haave your numbers please choose an operation (Mean, Median, or Mode!)
    Enter your choice here: Mode
    Counter({1: 1, 2: 1, 3: 1, 4: 1})