user3921890
user3921890

Reputation: 191

how to keep previous input

how do i keep previous input after i enter a new one? i want to make a list(not the built-in function) that keeps previous inputs and the most recent input...

my problem is when i enter an input after a previous one -it erases the previous and replaces it with the recent input

this is the smaller version of my current code:

enter = 1
count = 1
ctr = 0
max_input = 3


while ctr < max_input:

    for enter in range(1, max_input+1):
        if enter <= ctr:
            print("input " + str(enter) + ": " + str(user_input))
        else:
            print("input " + str(enter) + ": ___________" )

    user_input = int(input("enter number " + str(count) + ": "))

    enter += 1
    ctr += 1

this outputs:

input 1: ___________
input 2: ___________
input 3: ___________
enter number 1: 1
input 1: 1
input 2: ___________
input 3: ___________
enter number 2: 2
input 1: 2
input 2: 2
input 3: ___________
enter number 3: 3

expected output:

#the list before entering first number
input 1: ___________
input 2: ___________
input 3: ___________
enter number 1: 1

#the list after entering first number
input 1: 1
input 2: ___________
input 3: ___________
enter number 2: 2

#the list after entering second number
input 1: 1
input 2: 2
input 3: ___________
enter number 3: 3

#the list after entering last number
input 1: 1
input 2: 2
input 3: 3

Upvotes: 1

Views: 6272

Answers (1)

TheSoundDefense
TheSoundDefense

Reputation: 6935

Instead of continually printing and overwriting user_input, which will have its old content deleted whenever you reassign it, you should store the data in a list. This lets you store multiple values in the same data structure. Here's an example of your code using lists instead:

# enter = 1    This line doesn't serve any purpose.
count = 1
ctr = 0
max_input = 3
input_list = []


while ctr < max_input:

    for enter in range(0, max_input):
        if enter < ctr:
            print("input " + str(enter+1) + ": " + str(input_list[enter]))
        else:
            print("input " + str(enter+1) + ": ___________" )

    user_input = int(input("enter number " + str(count) + ": "))
    input_list.append(user_input)

    # enter += 1      This line doesn't serve any purpose.
    ctr += 1

We still save the input to user_input, but then it's added to input_list, which stores an increasingly large number of values. You access the first element with input_list[0], the next with input_list[1], and so on. Notice that the first element of a list is at index 0, not 1.

Upvotes: 2

Related Questions