我在这里研究了这个问题我发现了类似的问题,但这是不同的。我需要在我正在处理的代码片段中验证用户输入,如果用户输入低于0(这我工作正常),则需要打印错误,如果输入是非数字,则打印错误。问题是。如果我使用输入而不是raw_input我会收到错误:
NameError name 'Whatever I type in' is not defined
到目前为止我尝试了什么:
将变量转换为整数并尝试使用isNaN函数,但失败了,最后使用ifs和elses解决问题。这是迄今为止有效的代码。
def pints_to_litres():
pints = 0
pints = input("Please enter the amount of Imperial Pints you would like converted into Litres >>>")
litres = pints * float(0.568261)
litres = "%.2f" % litres
print (""+str(pints)+ " Pint(s) is equal to " +str(litres)+ " Litre(s)")
if (pints < 0):
print("Invalid Input! Try Again")
pints_to_litres()
提前谢谢你们 彼得罗曼尼克
答案 0 :(得分:3)
这里我改进了你的代码:
def pints_to_litres():
over = False
while not over:
try:
pints = int(raw_input("Please enter the amount of Imperial Pints you would like converted into Litres >>>"))
litres = pints * float(0.568261)
print (""+str(pints)+ " Pint(s) is equal to " +str(litres)+ " Litre(s)")
if (pints < 0):
print("Invalid Input! Try Again")
else:
over = True
except ValueError:
print("Invalid Input! Try Again")
pints
; raw_input
input
的使用,转而使用专为此目的设计的raw_input
; ValueError
再次转换品脱和循环时抛出int()
; 答案 1 :(得分:1)
pints = raw_input("Please enter the amount of Imperial Pints you would like converted into Litres >>>")
try:
pints = float(pints)
except ValueError:
print("Invalid Input! Try Again")
pints_to_litres()
然后继续代码
答案 2 :(得分:1)
试试这个:
try:
pints = float(raw_input("Please enter the amount of Imperial Pints you would like converted into Litres >>>\n"))
# Calculation ...
except ValueError:
print "Error"
答案 3 :(得分:0)
您可以使用.isdigit()
尝试此
entry =raw_input("Please enter the amount of Imperial Pints you would like converted into Litres >>>")
if (not( entry.isdigit())):
print "not a number"
pints_to_litres()
else:
pints=(int)(entry)