connor zinda
connor zinda

Reputation: 13

How to remove spaces from input and keep input as single entry

My homework assignment is to make a program that takes user input and adds it to a list before returning several values.

However, the homework has a stipulation that if the user enters spaces before or after an entry it should accept it. I am also running into the problem that my answers are being split up (entering 24 puts 2 and 4 in the list).

def main():
    done = False
    userNum = []
    num = 0
    print("Please enter to numbers to find the min/max value, sum, and number of entries.")
    while not done:
        listAdd = input("Please enter a number. When done press enter: ")
        userNum += listAdd
        if not listAdd:
            break
        userNum = list(map(int, userNum))
        num += 1

    print("Your list is: ", userNum)
    print("The amount of numbers entered: ", num)

    #max
    max = 0
    for i in userNum:
        if i > max:
            max = i
    print("Your maximum value of the list is: ", max)

    #min
    mini = 1
    for i in userNum:
        if i < mini:
            mini = i
    print("Your minimum value of the list is: ", mini)

    #average
    avgList = 0
    count = 0
    while count < num:
        avgList += userNum[count]
        count += 1
    print("The average value of your function is: ", avgList / num)

The code runs fine and gives back the expected values. I only have the 2 problems mentioned earlier.

I assumed it was because of the map function, which I'm unfamiliar with, but I used it to convert to strings. How can I fix them?

Upvotes: 0

Views: 75

Answers (3)

Matthew Barlowe
Matthew Barlowe

Reputation: 2328

The problem is when you add the string taken from the input to the list. When you add them together using the + it takes each element of the string and adds them individually to the list. The proper way to add a whole element to the list is the .append() method. Also when you map int later to the list is when the spaces are getting stripped out as well.

Upvotes: 0

Nuqie Noila
Nuqie Noila

Reputation: 71

When getting the input, use int(listAdd) to change it into integer, then just adding it to the array by using append function. Hence,

userName.append(int(listAdd))

Upvotes: 0

Cailan
Cailan

Reputation: 86

You can cast listAdd to an int/float depending on which is appropriate instead of using map. This will also keep multiple digit numbers together. If you are entering multiple numbers separated by spaces or other characters you will need to split them up first.

listAdd = int(listAdd)

int(' 5') will return 5 for example

or

listAdd = float(listAdd)

float(' 5') will return 5.0 for example

Upvotes: 1

Related Questions