python - Python 中的异常处理

标签 python

<分区>

我正在尝试在循环中创建异常处理。

我已经创建了以下代码,我想在 userId1 和 userid2 中放置一个异常(exception)。

例如,用户总数是943,那么当用户输入一个大于943的userId时,抛出一个异常消息'Sorry, this userId does not exist'并重新开始循环.

我试着用 try: 和 except KeyError: 但没有正确播放,或者我没有按正确的顺序书写。

怎么写呢?

exit=False
while exit is False:
    print("Hello Lady or Gentleman, this is a very primitive movie recommnedation system, please follow the instructions below : ")
    print("---------------------------------------------------------------------------")
    print("1) If you would like to find the difference 1 please press 1")
    print("2) If you would like to find the difference 2 please press 2")
    print("3) If you would like to exit, then press 0")

    option=False
    while option is False:
        print("Εnter what would you like to find please :",end=" ")
        option=input();
        if option =='1':
            print("The total number of users is 943, so you should enter 2 user_ids lower than 944")
            print('---------------------')
            print("Enter the first userId please :",end=" ")
            user1 = input();
            print("Enter the second userId please :",end=" ")
            user2 = input();
        elif option == '2':
            print("The total number of movies is 1682, so you should enter 2 movie_ids lower than 1683")
            print('-------------------')
            print("Enter the first bookId please :",end=" ")
            bookId1 = input();
            print("Enter the second bookId1 please :",end=" ")
            bookId2= input();
        elif option == '0':
            exit = True
            print("Thank you very much")
            break
        else:
            option = False
            print("This option is not valid, Please try again!")

最佳答案

使用continue 语句返回到循环的开始。

if int(user1) > 943:
    print('Sorry, this userId does not exist')
    continue

关于python - Python 中的异常处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59111961/

相关文章:

python - 查找列与另一列中的多个匹配的位置

python - 这个 List Overlap 程序给出了奇怪的输出

Python3找到最后一次出现的字符串然后写入

javascript - 使用 jQuery 和变量的问题

java - 将列表分成组

python - 在同一模型中注释给出意想不到的结果

python - 类型错误 : Object of type bool_ is not JSON serializable

即使列丢失,python 切片也不会给出键错误

python - 警告 : You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near

python - Spark : How to "reduceByKey" when the keys are numpy arrays which are not hashable?