Search code examples
pythonuser-input

Simple code to get inputs from user and then print them all at once not working?


I'm new to python and was doing a few "simple python tasks" to get started. I wrote a code to get a few numbers from the user and then after the user gives all numbers it prints them all. This is my code:

number = [4]
for i in range(5):
    number[i] = int(input(f"Input number {i}: "))
print("Your numbers are: ", number)

The code works nicely for the first input, but after the second number is inputed it says there's in error in line 3. I have no idea why, but I'm gussing it has to do with the list (this is my first time using a list, idk how to define it and such).

Thanks in advance <3

To get 5 inputs from the user and lastly print them out in a single "your numbers are: ".


Solution

  • Error reason: number is initialized as a list with a single element [4]. Since the loop tries to access indices beyond the first index of the list, it will result in an IndexError

    Code:

    number=[]
    for i in range(5):
        number.append(int(input(f"Input number {i+1}: ")))
    print("Your numbers are: ", number)
    

    Output:

    Input number 1: 5
    Input number 2: 7
    Input number 3: 4
    Input number 4: 2
    Input number 5: 1
    Your numbers are:  [5, 7, 4, 2, 1]