2014-05-08 195 views
1

我在这里研究了这个问题我发现了类似的问题,但这是不同的。我需要在我正在处理的代码片段中验证用户输入,如果用户输入不是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() 

谢谢你们提前 彼得Romaniuk

+0

不知道为什么编辑,这是Python代码。 – user3578634

+1

你为什么不用'raw_input'? – honi

+0

我仍然遇到raw_input出错“TypeError:无法乘以类型'float'的非int的序列” – user3578634

回答

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") 
  • 的没用设置用raw_input覆盖之前;
  • 更改使用input有利于为此设计的raw_input;
  • 如果该字符串无效,则会在int()再次转换品质和循环时抛出ValueError;
  • 如果值太低,则会再次循环;
  • 正如你所看到的,我也改变了对函数的递归调用,就好像用户总是失败一样,你最终会粉碎函数堆栈限制,并且失败。
+1

谢谢你!这是完美的,完美的作品,最好的我现在可以看到我错了那么多谢谢:) – user3578634

+0

哈哈。作为答案一次,“谁会输入999999次数字?”“谁知道?也许你会的。“顺便说一句,错误被称为RuntimeError。 – thecoder16

+0

这不是因为它不可能发生,它**不能**发生!你永远不知道将来如何使用代码,你应该始终尽可能地使用代码! – zmo

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() 

然后用代码

+0

这是不好的编程来递归一个函数,没有做适当的递归。 – zmo

+1

同意。你的答案好多了。我尽可能少地改变op的代码 – honi

+1

感谢您的帮助honi我设法用@zmo的修复来修复它。谢谢你试图帮助我,我非常感谢:) – user3578634

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" 
+0

谢谢josip_grg它现在已被修复。感谢您的帮助。作为初学者,任何帮助都是有帮助的,并教会我一些东西。 – user3578634

0

您可以检查是否输入的是数字BU使用.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)