2016-12-29 3 views
-4

私はtry-exceptを使用してユーザーに数字を入力させようとしていますが、効果はないようです。実際Try-Except ErrorCatching

while count>0: 
    count=count - 1 
    while (length != 8): 
     GTIN=input("Please enter a product code ") 
     length= len(str(GTIN)) 
     if length!= 8: 
      print("That is not an eight digit number") 
      count=count + 1 
     while valid == False: 
      try: 
       GTIN/5 
       valid = True 
      except ValueError: 
       print("That is an invalid number") 
       count=count + 1 

答えて

1

、例えばユーザ入力文字列、"hello"/5TypeErrorをもたらし、ないValueError、その代わりに

0

あなたはValueErrorを発生させ、入力値INT int(value)を、作ってみることができキャッチした場合それが変換できない場合。

ことはここではいくつかのコメントをしたい何をすべき機能です:

def get_product_code(): 
    value = "" 
    while True: # this will be escaped by the return 
     # get input from user and strip any extra whitespace: " input " 
     value = raw_input("Please enter a product code ").strip() 
     #if not value:   # escape from input if nothing is entered 
     # return None 
     try: 
      int(value)   # test if value is a number 
     except ValueError:  # raised if cannot convert to an int 
      print("Input value is not a number") 
      value = "" 
     else:     # an Exception was not raised 
      if len(value) == 8: # looks like a valid product code! 
       return value 
      else: 
       print("Input is not an eight digit number") 

定義されたら、あなたはまた除く外にしてくださいする必要があり、ユーザ

product_code = get_product_code() 

からの入力を取得する関数を呼び出します^Cなどのプログラムをクラッシュさせる可能性があるため、ユーザーの入力が必要な場合はいつでも、KeyboardInterruptを処理してください。

product code = None # prevent reference before assignment bugs 
try: 
    product_code = get_product_code() # get code from the user 
except KeyboardInterrupt: # catch user attempts to quit 
    print("^C\nInterrupted by user") 

if product_code: 
    pass # do whatever you want with your product code 
else: 
    print("no product code available!") 
    # perhaps exit here 
+0

これをどのように呼びますか? – TheLegend27

+0

一度定​​義すると、他の関数と同じ方法で呼び出すことができます。 [そのプロセスと使い方についてはかなり良い説明があります](https://docs.python.org/3/tutorial/controlflow.html#defining-functions) – ti7

+0

ああ、私は今見ていますが、私はこれをコード、シェルではありません。私は私のニーズにこれを適応させることができますが表示されます、ありがとう – TheLegend27