Skip to content
Advertisement

How do I restrict the user input to particular strings, which are already stored as a variable(s)?

I am creating a web-scraping tool for some gift cards, and I have stored the name of each gift card (which is a string, i.e “PSN”) as a variable. So for example, P = “PSN”

I have a user input asking them to put in the name of the card they’re after, but I want it to be restricted to the variables I have already defined, so that if they type a name other than the cards I have already allowed for, it will return an error and ask them to type the name again.

How can I go about this?

Here is the code I’ve written so far:

#Stored strings for each card
    G = "Google".casefold()
    P = "PSN".casefold()
    X = "Xbox".casefold()
    I = "iTunes".casefold()
    N = "Nintendo".casefold()
    A = "Amazon".casefold()
    S = "Steam".casefold()

    Card_Name = input('Enter Card Name:') 
    cardnameanswer = G, P, X, I, N, A, S
    Card_Name = cardnameanswer

Advertisement

Answer

Like this:

G = "Google".casefold()
P = "PSN".casefold()
X = "Xbox".casefold()
I = "iTunes".casefold()
N = "Nintendo".casefold()
A = "Amazon".casefold()
S = "Steam".casefold()

while True: # Keeps looping unless specified
    Card_Name = input('Enter Card Name:')
    if Card_Name in [G, P, X, I, N, A, S]: # If the card name entered is amoung the valid names
        break # Break out of the loop, without continuing the rest of the loop
    print('Invalid card name.') # Only prints if the user haven't broke out of the loop
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement