2017-03-06 70 views
0

這是我的代碼:如何處理錯誤的輸入(輸入非數字值)?

def calc_area(radius): 
    return (radius **2) * (math.pi) 

def calc_circ (radius): 
    return (math.pi * radius) * 2 

radius = float(input('Please enter the cirlcle\'s radius: ')) 
print ('The area of the the circle is', calc_area(radius), 'and the circumference is', calc_circ(radius)) 

我能做些什麼,以確保用戶不會鍵入一個字母?

回答

1

在進行任何計算之前,請嘗試檢查用戶輸入以確保他們提交了一個數字。

try: 
    value = int(userInput) 
except ValueError: 
    print("That's not an int!") 

或者你的情況:

def calc_area(radius): 
    return (radius **2) * (math.pi) 

def calc_circ (radius): 
    return (math.pi * radius) * 2 

try: 
    radius = float(input('Please enter the cirlcle\'s radius: ')) 
    print ('The area of the the circle is', calc_area(radius), 'and the circumference is', calc_circ(radius)) 
except ValueError: 
    print("That's not a number!") 
0

在這裏,你可以使用嘗試捕捉也!

ip = input('Please enter the cirlcle\'s radius: ') 
if isinstance(ip, int): 
    temp = float(ip) 
0

我個人比較喜歡的斷言語句

def calc_area(radius): 
    assert isinstance(radius, int) or isinstance(radius, float), "Radius must be a number." 
    return (radius **2) * (math.pi) 

當用戶試圖在比其他一些東西通過,他們得到這樣的:

>>> calc_area("a") 
Traceback (most recent call last): 
    File "<pyshell#5>", line 1, in <module> 
    calc_area("a") 
    File "<pyshell#1>", line 2, in calc_area 
    assert isinstance(radius, int) or isinstance(radius, float), "Radius must be a number." 
AssertionError: Radius must be a number. 

尼斯能夠增加如果稍後使用代碼,則嘗試/ catch語句,但其他答案僅適用於與簡單用戶交互的情況。