あなたは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
出典
2016-12-29 17:30:26
ti7
これをどのように呼びますか? – TheLegend27
一度定義すると、他の関数と同じ方法で呼び出すことができます。 [そのプロセスと使い方についてはかなり良い説明があります](https://docs.python.org/3/tutorial/controlflow.html#defining-functions) – ti7
ああ、私は今見ていますが、私はこれをコード、シェルではありません。私は私のニーズにこれを適応させることができますが表示されます、ありがとう – TheLegend27