Skip to content Skip to sidebar Skip to footer

Adding Multiple Elements To A List In Python

I am trying to write something in Python that will be like a piano. Each number that the user enters will play a different sound. The user is prompted for how many keys they want

Solution 1:

The first thing you should do in your function is initialize an empty list. Then you can loop the correct number of times, and within the for loop you can append into myList. You should also avoid using eval and in this case simply use int to convert to an integer.

defuserNum(iterations):
    myList = []
    for _ inrange(iterations):
        value = int(input("Enter a number for sound: "))
        myList.append(value)
    return myList

Testing

>>> userNum(5)
Enteranumberforsound: 2Enteranumberforsound: 3Enteranumberforsound: 1Enteranumberforsound: 5Enteranumberforsound: 9[2, 3, 1, 5, 9]

Solution 2:

def userNum(iterations):

number_list = []

while iterations > 0:
    number = int(input("Enter a number for sound : "))
    number_list.append(number)
    iterations = iterations - 1return number_list

print "Numbers List - {0}".format(userNum(5))

Enter a number for sound : 9

Enter a number for sound : 1

Enter a number for sound : 2

Enter a number for sound : 0

Enter a number for sound : 5

Numbers List - [9, 1, 2, 0, 5]

Solution 3:

You can simply return a list comp:

defuserNum(iterations):
    return [int(input("Enter a number for sound: ")) for _ inrange(iterations) ]

If you were using a loop you should use a while loop and verify input with a try/except:

defuser_num(iterations):
    my_list = []
    i = 0while i < iterations:
        try:
            inp = int(input("Enter a number for sound: "))
        except ValueError:
            print("Invalid input")
            continue
        i += 1
        my_list.append(inp)
    return my_list

Post a Comment for "Adding Multiple Elements To A List In Python"