Ozakriid
Ozakriid

Reputation: 7

I am having an issue with my while loop, not too sure why

I was coding a little loop to stop users from using invalid input; however, now if they enter a faulty input, it continuously asks for their input. baseLet, secLet, thirdLet, and forLet are all lists with characters in them. The code is supposed to tell if the user inputs any characters not in any of the lists and make them re-enter their input if there are.

enchan = list(input("Enter your runes:"))

for z in enchan:
    if not(z in baseLet or z in secLet or z in thirdLet or z in forLet):
        valid = False


x = 0
while not(valid):
    x = 0
    enchan = list(input("Invalid character entered. Enter your runes:"))
    while not(x < len(enchan)):
        valid = True
        for z in enchan:
            if not(z in baseLet or z in secLet or z in thirdLet or z in forLet):
                valid = False
            x += 1

Forgive me, I am fairly new to coding, and there is a chance there is a stupid mistake, but that is the main reason I am here (to learn).

Upvotes: 1

Views: 60

Answers (1)

luigigi
luigigi

Reputation: 4215

This should work:

baseLet = ['a']
secLet = ['b']
thirdLet = ['c']
forLet = ['d']
valid = False

def is_valid(input_string):
    for s in input_string:
        if not(s in baseLet or s in secLet or s in thirdLet or s in forLet):
            print('false input')
            return False
    print('valid input')
    return True

while not valid:
    enchan = list(input("Enter your runes:"))
    valid = is_valid(enchan)

You can use a function to check if your input is part of your lists and set a flag to stop your while loop.

Upvotes: 1

Related Questions