Python 多个问题的用户输入不正确或没有
下面是一个程序,它要求用户输入字符串和int。如果有人输入错误的类型或根本没有输入,程序将以错误结束。我需要处理每个问题的例外情况。我该怎么做?我只需要一行“while true”吗?它能在一个街区内吗 谢谢, 马特Python 多个问题的用户输入不正确或没有,python,python-3.x,exception,Python,Python 3.x,Exception,下面是一个程序,它要求用户输入字符串和int。如果有人输入错误的类型或根本没有输入,程序将以错误结束。我需要处理每个问题的例外情况。我该怎么做?我只需要一行“while true”吗?它能在一个街区内吗 谢谢, 马特 我假设它仅适用于Int和Float类型的输入。然后可以通过以下方式实现: try: num1 = float(input("Enter float")) num2 = int(input("Enter Int"))
我假设它仅适用于
Int
和Float
类型的输入。然后可以通过以下方式实现:
try:
num1 = float(input("Enter float"))
num2 = int(input("Enter Int"))
print(num1,num2)
except ValueError:
print("Hey you have entered the wrong datatype")
听起来你应该做一个函数来提示输入,转换成所需的类型,如果失败了,那么发出一条消息再试一次。然后,您可以为每个数据项调用它(而不是直接调用
input
)。例如:
def get_input(prompt, type_=str):
while True:
try:
return type_(input(prompt))
except ValueError:
print(f"Bad input - type {type_.__name__} is needed - try again")
customerName = get_input("Customer Name: ")
L_Citrulline_Mallate = get_input("Amount of L-Citrulline: ", int)
L_Theanine = get_input("Amount of L-Theanine: ", float) / 1000
print(customerName, L_Citrulline_Mallate, L_Theanine)
如果您还想拒绝空字符串输入,那么您也可以对此进行测试。例如:
def get_input(prompt, type_=str, allow_empty=False):
while True:
response = input(prompt)
if response == "" and not allow_empty:
print("You must enter something")
continue
try:
return type_(response)
except ValueError:
print("Bad input - type {} is needed - try again".format(type_.__name__))
customerName = get_input("Customer Name: ")
comment = get_input("Any comment?: ", allow_empty=True)
由于您的输入都是在使用它们之前进行的,因此我建议在允许进一步执行之前对它们执行一些检查。在继续下一步之前,请验证收到的值是否与您期望的值一致。您应该能够做到这一点,而无需进行任何尝试/除外,而只需执行if/else。这是您的编程决策—您是否会收到准确的错误消息(
这是一个错误的输入,因为…
),或者更确切地说是一个一般性的错误消息(出现了错误。
)。前者显然涉及各种try/except
块,而后者只能由一个块组成。
def get_input(prompt, type_=str, allow_empty=False):
while True:
response = input(prompt)
if response == "" and not allow_empty:
print("You must enter something")
continue
try:
return type_(response)
except ValueError:
print("Bad input - type {} is needed - try again".format(type_.__name__))
customerName = get_input("Customer Name: ")
comment = get_input("Any comment?: ", allow_empty=True)