我的while循环有问题,不太清楚为什么

2024-09-27 23:21:49 发布

您现在位置:Python中文网/ 问答频道 /正文

我编写了一个小循环来阻止用户使用无效的输入;但是,如果用户输入了错误的输入,它会不断地要求用户输入。baseLet、secLet、thirdLet和forLet都是包含字符的列表。代码应该告诉用户是否输入了任何列表中没有的字符,如果有,则让他们重新输入。你知道吗

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

恕我直言,我对编码还比较陌生,有可能是一个愚蠢的错误,但这是我来这里(学习)的主要原因。你知道吗


Tags: or用户in列表input错误not字符
1条回答
网友
1楼 · 发布于 2024-09-27 23:21:49

这应该起作用:

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)

您可以使用一个函数来检查您的输入是否是列表的一部分,并设置一个标志来停止while循环。你知道吗

相关问题 更多 >

    热门问题