2017-10-04 52 views
0

我將如何在整個程序中使用該錯誤檢查程序,以便我可以檢查用戶是否輸入了正確的數據類型?我如何將ValueError作爲一個過程並用它來檢查年齡和名字?

def errorcheck(): 
    valid=False 
    while valid==False: 
     try: 
      ()=True 
     except ValueError: 
      print("Please enter an appropriate value") 
      valid=False 

errorcheckage=int(input("How old are you?")) 
forename=str(input("What is your firstname?")) 
username=forename[0:3]+age 
print(username) 
+0

可能的複製[確定對象的類型?(https://stackoverflow.com/questions/2225038/determine-the-type-of-an-object) – Mangohero1

+0

我會怎麼做呢?只需要在需要程序強健的評估中使用'isinstance'來獲得額外的分數 –

+0

。把你所有的輸入放到你的'try'塊中 – Mangohero1

回答

0

你可以編寫一個實現你的循環控制的包裝器,但它很詳細,可能不會節省你很多時間。的

def validator_loop(f: "function to run", 
        *args: "arguments to function", 
        validator=lambda _: True, 
        **kwargs: "kwargs for function"): 
    while True: 
     try: 
      result = f(*args, **kwargs) 
     except Exception as e: 
      continue # repeat if it throws any exception 
     else: 
      if validator(result): 
       return result 

# note that an entry of "zero" will fail this validation, even though 
# 0 is a valid age for some purposes! I'll leave this edge case for you 
checkage = validator_loop(input, "How old are you?", 
          validator=lambda s: int(s)) 
相關問題