我想编写一个代码,如果用户在显示的菜单中输入任何无效选项,它会要求用户输入有效选项,在本例中是整数 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:
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