如何检查用户输入是否为整数 [duplicate]

How do I check if the user input is an integer [duplicate]

提问人:Jenson Chai 提问时间:10/12/2023 更新时间:10/12/2023 访问量:46

问:

我想制作一个代码,如果用户在显示的菜单中输入了任何无效选项,它将要求用户输入一个有效选项,在本例中为整数 1-7。

但在这里,无论用户输入什么选项,它都会显示这是一个无效的选择。

def update_profile():
        while True:
            print("Choose the options below to update the info")
            print("1.Username\n2.Password\n3.Email\n4.Date of Birth\n5.Address\n6.Contact Number\n7.Exit")
            choice = input("Enter your choice:")

            try:
                int(choice)
            except ValueError:
                pass

            match choice:
                case 1:
                   ...
                case 2:
                   ...
                case _:
                   print("Invalid choice. Please select again.")
                   print("--------------------------------------------")
                   continue
            repeat = input("Do you want to continue update the profile? <Yes [Y]\tNo [N]>\nYour choice: ")
            if repeat == 'N' or repeat == 'n':
                break  

输出:

Choose the options below to update the info
1.Username
2.Password
3.Email
4.Date of Birth
5.Address
6.Contact Number
7.Exit
Enter your choice:1
Invalid choice. Please select again.
--------------------------------------------
Choose the options below to update the info
1.Username
2.Password
3.Email
4.Date of Birth
5.Address
6.Contact Number
7.Exit
Enter your choice:
Python 输入 整数 字符 序列

评论

3赞 Matthias 10/12/2023
int(choice)不会改变。它返回一个整数,但您忽略返回的值。你需要。choicechoice = int(choice)
1赞 Codist 10/12/2023
为什么不直接将选项用作字符串呢?无需将它们转换为整数

答:

0赞 rumpel360 10/12/2023 #1

int() 不会更改其参数值,而是返回结果。 因此,在异常处理块中,您可以分配一个新变量并将其用于匹配块。

def update_profile():
while True:
    print("Choose the options below to update the info")
    print("1.Username\n2.Password\n3.Email\n4.Date of Birth\n5.Address\n6.Contact Number\n7.Exit")
    choice = input("Enter your choice:")
    try:
        choice_int = int(choice)
    except ValueError as e:
        print(e)
        pass

    match choice_int:
        case 1:
            ...
        case 2:
            ...
        case _:
            print("Invalid choice. Please select again.")
            print("--------------------------------------------")
            continue
    repeat = input("Do you want to continue update the profile? <Yes [Y]\tNo [N]>\nYour choice: ")
    if repeat == 'N' or repeat == 'n':
        break