2013-03-08 77 views
-1
print("this program will calculate the area") 

input("[Press any key to start]") 

width = int(input("enter width")) 

while width < 0 or width > 1000: 
    print ("please chose a number between 0-1000") 
    width = int(input("enter width")) 

height = int(input("Enter Height")) 

while height < 0 or height > 1000: 
    print("please chose a number between 0-1000") 
    widht = int(input("Enter Height")) 

area = width*height 

print("The area is:",area 

消息我添加了一個錯誤消息用於輸入數字更低或更高然後說明,但是如果可能的話我想,如果他們輸入來顯示錯誤消息給用戶信或根本沒有。Python-整數輸入,誤差用於輸入字母

+0

好的,所以你需要編寫一些代碼來做到這一點。這裏沒有。 – 2013-03-08 00:38:20

+1

第15行:您拼寫的「高度」錯誤爲寬度,但仍然錯誤。 – ApproachingDarknessFish 2013-03-08 00:50:40

回答

4

嘗試換線路輸入線一試,除了:

try: 
width = int(input("enter width")) 
except: 
width = int(input("enter width as integer")) 

或更好:在一個函數把它包:

def size_input(message): 
    try: 
     ret = int(input(message)) 
     return ret 
    except: 
     return size_input("enter a number") 

width = size_input("enter width") 
2

您可以使用try-exceptint()提出如果參數異常傳遞給它無效:

def valid_input(inp): 
    try: 
     ret=int(inp) 
     if not 0<ret<1000: 
      print ("Invalid range!! Try Again") 
      return None 
     return ret 
    except: 
     print ("Invalid input!! Try Again") 
     return None 
while True: 
    rep=valid_input(input("please chose a number between 0-1000: ")) 
    if rep:break 
print(rep) 

輸出:

please chose a number between 0-1000: abc 
Invalid input!! Try Again 
please chose a number between 0-1000: 1200 
Invalid range!! Try Again 
please chose a number between 0-1000: 123abc 
Invalid input!! Try Again 
please chose a number between 0-1000: 500 
500