Anya
Anya

Reputation: 395

How do you store two different inputs from the same variable?

    while n == 1:
        w = input("Input the product code: ")   

Problem is that when a new code for w is entered, w is overwritten. For example, if w = 24, then w = 54, if you print(w) it will just print 54, since it's the latest input. How do you make it so that it prints all inputs for w?

Upvotes: 3

Views: 998

Answers (3)

Aiden Grossman
Aiden Grossman

Reputation: 347

You can do this in two separate ways but the way you are trying to do it will not work. You cannot have a variable that is not a list hold two values.

Solution 1: use two variables

w1 = input("value1")
w2 = input("value2")
print(w1)
print(w2)

Solution 2: use a list

w = []
w.append(input("value1"))
w.append(input("value2"))
print(w[0])
print(w[1])

Upvotes: 0

Chris
Chris

Reputation: 22953

Use a container type instead of a single variable. In this case, list() would seem appropriate:

inputs = [] # use a list to add each input value to
while n == 1:
    inputs.append(input("Input the product code: ")) # each time the user inputs a string, added it to the inputs list
for i in inputs: # for each item in the inputs list
    print(i) # print the item

Note: The above code will not compile. You need to fill in the value for the variable n.

Upvotes: 1

Patrick Haugh
Patrick Haugh

Reputation: 60974

inputs = []
for i in range(expected_number_of_inputs):
    inputs.append(input('Product Code: '))
for i in inputs:
    print(i)

Upvotes: 1

Related Questions