You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用While True进行输入验证时的错误提示异常问题求助

问题原因

你的代码问题出在:当输入0或1这类有效选项时,代码会将choice转换为整数类型,处理完对应操作后,while True循环会继续执行下一轮判断。此时choice是整数(比如0),而判断条件是检查它是否在字符串列表['0','1',...]中,整数和字符串不相等,所以会触发无效输入的错误提示。

修复方案

以下两种修复思路任选其一即可:

思路1:保留字符串判断,操作后重新获取输入

用新变量存储整数类型的选项,不修改原choice的字符串类型,处理完操作后重新获取输入,确保下一轮判断类型匹配:

def main():
    print('\nDear user, welcome to the Online library of Husam.\nPlease choose from the option menu below: ')
    
    print(""" ======LIBRARY MENU=======
   0. To create a book and add it to the book list.
   1. To create a user and add it to the user list.
   2. To Display the current books in the library.
   3. To Display the current users in the library.
   4. Search for a book using: title, author, publisher, or publication date.
   5. Remove a book using: title.
   6. Display total number of books in the library.
   7. Remove a user from the system using: firstname.
   8. Display the number of the users in the system.
   9. Display a user's details using: username.
   10. Borrow a book.
   11 Return a book.
   12. Display number of books a user is borrowing.
   13. Display overdue books that need to be returned.
   14. Exit the system.
                  
                  """)
    choice = input("How may we serve you today? Please choose a number between 0 and 14: \n")
    while True:
        if choice not in ['0','1','2','3','4','5','6','7','8','9','10','11','12','13','14']:
            print('Error: Invalid input! Please type in only a number between 0 and 14: ')
            choice = input('\nHow may we serve you today? Please choose a number between 0 and 14: \n')
        else:
            choice_int = int(choice)
            
            if choice_int == 0:
                print(0)
            elif choice_int == 1:
                print(1)
            elif choice_int == 2:
                print('The Library currently has the following books in it: \n')
                print(2)
            elif choice_int == 3:
                print('The Library currently has the following users in it: \n')
                print(3)
            elif choice_int == 4:
                print(4)
            elif choice_int == 5:
                print(5)
            elif choice_int == 6:
                print(6)
            elif choice_int == 7:
                print(7)
            elif choice_int == 8:
                print(8)
            elif choice_int == 9:
                print(9)
            elif choice_int == 10:
                print(10)
            elif choice_int == 11:
                print(11)
            elif choice_int == 12:
                print(12)
            elif choice_int == 13:
                print(13)
            elif choice_int == 14:
                print(14)
                break
            
            # 处理完操作后重新获取输入
            choice = input('\nHow may we serve you today? Please choose a number between 0 and 14: \n')

main()

思路2:统一使用整数判断,增强鲁棒性

直接将输入转为整数,用range(0,15)简化判断逻辑,同时处理用户输入非数字的错误情况:

def main():
    print('\nDear user, welcome to the Online library of Husam.\nPlease choose from the option menu below: ')
    
    print(""" ======LIBRARY MENU=======
   0. To create a book and add it to the book list.
   1. To create a user and add it to the user list.
   2. To Display the current books in the library.
   3. To Display the current users in the library.
   4. Search for a book using: title, author, publisher, or publication date.
   5. Remove a book using: title.
   6. Display total number of books in the library.
   7. Remove a user from the system using: firstname.
   8. Display the number of the users in the system.
   9. Display a user's details using: username.
   10. Borrow a book.
   11 Return a book.
   12. Display number of books a user is borrowing.
   13. Display overdue books that need to be returned.
   14. Exit the system.
                  
                  """)
    while True:
        try:
            choice = int(input("How may we serve you today? Please choose a number between 0 and 14: \n"))
            if choice not in range(0, 15):
                print('Error: Invalid input! Please type in only a number between 0 and 14: ')
            else:
                if choice == 0:
                    print(0)
                elif choice == 1:
                    print(1)
                elif choice == 2:
                    print('The Library currently has the following books in it: \n')
                    print(2)
                elif choice == 3:
                    print('The Library currently has the following users in it: \n')
                    print(3)
                elif choice == 4:
                    print(4)
                elif choice == 5:
                    print(5)
                elif choice == 6:
                    print(6)
                elif choice == 7:
                    print(7)
                elif choice == 8:
                    print(8)
                elif choice == 9:
                    print(9)
                elif choice == 10:
                    print(10)
                elif choice == 11:
                    print(11)
                elif choice == 12:
                    print(12)
                elif choice == 13:
                    print(13)
                elif choice == 14:
                    print(14)
                    break
        except ValueError:
            print('Error: Invalid input! Please type in only a number between 0 and 14: ')

main()
说明
  • 思路1保留原逻辑框架,仅调整变量使用方式,适合希望最小改动代码的场景。
  • 思路2更简洁高效,还能处理用户输入非数字的错误,整体鲁棒性更强。

内容的提问来源于stack exchange,提问作者luca kramp

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 20:57:25