gpt4 book ai didi

Python-不希望字母或数字超出输入范围

转载 作者:太空宇宙 更新时间:2023-11-03 18:02:22 24 4
gpt4 key购买 nike

我希望程序只允许使用数字 1-4 作为输入,而不允许使用该范围之外的任何字母或数字。这是我现在的代码,但它不起作用:

 # Get the user's choice.
choice = int(input("what would you like to do ? "))

# Validate the choice.
while choice < 1 or choice > 4:
try:
choice = int(raw_input("Enter a valid choice: "))
except ValueError:
print ("Please enter a numeric value.")

# return the user's choice.
return choice

最佳答案

这是您的解决方案

while True:
try:
choice = int(input("what would you like to do ? "))
except ValueError:
print ("Invalid choice.Valid choises are between 1-4.")
continue
if choice<1 or 4<choice:
print ("Invalid choice.Valid choises are between 1-4.")
continue
else:
print ("some codes will work on here..")

关于Python-不希望字母或数字超出输入范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27474109/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com