2017-03-06 55 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语句,但其他答案仅适用于与简单用户交互的情况。