Search code examples
pythonlistinputstring-concatenation

Python: Detecting non-specific inputs in lists


My list is appended through selection. Basically, I ask a question, and whatever you input is what goes into this list.

I also ask how many of whatever you input. This created duplicates, so I used a concatenation to add an incremental number if the amount you entered is greater than one. (for example,

"What would you like to add to the list?" User: "dog" "How many?" User: "3"

list = dog, dog2, dog3, cat)

For my specific program, there is no way of me knowing what the user might input, so I can't use if ____ in _____ Can I? Also, now I have these concatenated strings named 'dog' and a number. I just want the code to detect dog, within the list, but again, I don't know if dog is even in the list! It could be anything!


Solution

  • From the description and the comments, here is a sample code which you need, I am creating a dict, and storing the item as key and the count as the value.

    item = input("What would you like to add to the list?") # User Input : Dog
    cnt = int(input("How many?")) : User Input : 3
    
    d = {item:cnt} # dict created {'dog': '3'}
    
    def callFunctionNtimes(d, key):
        """
        Function which check the key (dog) is present in the dict, if it is present call callYourFunction as many times as it is the value(count) of the key.
        """
        cnt = d.get(key, 0)
        for c in range(0, cnt):
            callYourFunction()