Reputation: 67
I am a beginner to python and I encountered a problem. This is what I wanted to do: If I I have 1 line that contains an input statement. while repeating the same line a few times by a loop, I want to store the data from the input and saving it from every repetition without loosing the previous data. after finishing the loop, I want to retrieve the data from all the iterations of the loop and then do something with each different data. In my case what I want to do is to compare the data. now the problem is that I were not able to save and store the data.
for i in range(2):
x = input("give me a letter")
if(x1==x2):
#the x1 and x2 are only for demonstrating that they should be different variables from x. they are not real syntax
print("you wrote the same letter twice!")
I tried to see if I can use the pickle model, but wasn't able to understand how to do so.
Upvotes: 0
Views: 162
Reputation: 124
I'm a little unclear as to what you are attempting to accomplish. Are you, as LucasBorges-Santos interprets your question, capturing the space separated responses from a single query or are you capturing separate inputs from the query "Give me a letter" than runs 'n' times in a loop? If the latter, you can create an empty list, run your input in a loop (as you have done) and append each response to the list. Then with the list of responses you can perform whatever operations you desire. You can, if you like, check for duplicates inside your loop and append only non-duplicate responses. Maybe something like this:
answers = []
for _ in range(3):
x = input("Give me a letter: ")
if x in answers:
print("Duplicate")
else:
answers.append(x)
print(answers)
You can also build in some input validation if you really want to limit valid responses to single alphabetic characters, testing the inputs by checking the length of the input and testing against .isalpha().
answers = []
for _ in range(3):
x = input("Give me a letter: ")
if len(x) > 1 or not x.isalpha():
print("Must be a single letter.")
elif x in answers:
print("Duplicate entry")
else:
answers.append(x)
print(answers)
Upvotes: 0
Reputation: 19
You can store using a list and add to that list and keep on comparing data to it:
listNumbers = []#Creates a list to check the values you input
while True: #Creates a loop forever
x = input("Give me a something: ")
if x in listNumbers:#Checks if the piece of data is in that list
print("You wrote the same data twice!")
elif len(listNumbers) >= 0:#This is to add to the list forever if its a new character
listNumbers.append(x)#If it's new then it will add to the list
print(listNumbers)#For visually checking your list
Upvotes: 1
Reputation: 392
U can use split:
# we suppose input is -> 1 2 3 4 u
>>> (*i, j) = input().split()
>>> print(i)
['1', '2', '3', '4']
How to declare variables from an input() with different class ( int and str)
Upvotes: 1