在函数中捕获用户输入的错误

2024-04-20 06:44:05 发布

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

我一直在努力使用这个函数来捕获用户输入的错误

def user_choice():
            choice = 4
            while choice > 3
                    choice = int(input("what list is your card in"))
            return choice

任何想法都将不胜感激。 谢谢


Tags: 函数用户ininputyourisdef错误
1条回答
网友
1楼 · 发布于 2024-04-20 06:44:05

这可以简单地通过使用所需的有效参数实现一个数组,然后使用in关键字检查它是否存在

def user_choice():
        choice = int(input('what list is your card in?: '))
        valid = [1,2,3]
        if choice in valid:
            return choice
        else: 
            print('oops! must be between 1-3 please try again')
            user_choice()

相关问题 更多 >