如何处理错误输入(输入非数值)?

时间:2017-03-06 04:11:54

标签: python

这是我的代码:

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))

如何确保用户不输入字母?

3 个答案:

答案 0 :(得分:1)

在进行任何计算之前,请尝试检查用户输入以确保他们提交了一个数字。

$(".test").click(function(){
  console.log("name: ", $(this).closest('tr').index()-1);
});  

或者在你的情况下:

$(".test").click(function(){
  console.log("name: ", $('#sum_table tr:not(.titlerow)').index($(this).closest('tr')));
}); 

答案 1 :(得分:0)

在这里,您也可以使用try catch!

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

答案 2 :(得分: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.

如果稍后使用代码,可以添加try / catch语句,但其他答案更适合与简单用户进行交互。

相关问题