如何输入只取数字

时间:2012-12-30 12:03:29

标签: python-3.x

我无法在互联网上找到这个问题的解决方案(也许我看起来不够努力),但我无法弄清楚如何只输入数字。我试图让输入通过一些方程式,每当我在输入中输入一个字母时程序就会制动。我想知道是否有办法检测输入是字母还是数字。我会展示我的节目。

    Radius=input("What is the radius of the circle/sphere?")

    Areacircle=(int(Radius)**2)*3.14159265359
    Perimetercircle=2*3.14159265359*int(Radius)
    Permsphere=4*3.14159265359*(int(Radius)**2)
    Areasphere=(4/3)*3.14159265359*(int(Radius)**3)

    print("The radius' length was:",Radius)
    print("The surface area of each circle is:",Areacircle)
    print("The perimeter of the circle is:",Perimetercircle)
    print("The volume of the sphere would be:",Areasphere)
    print("The perimeter of the Sphere would be:",Permsphere)

1 个答案:

答案 0 :(得分:1)

根据评论中的建议,当handle失败时,您可以ValueError conversion to int {并保存在其余代码中执行相同的转换。)

Radius = None
while not Radius:
    unchecked_radius = input("What is the radius of the circle/sphere? ")
    try:
        Radius = int(unchecked_radius)
    except ValueError:
        print('"{}" is not an integer. Redo.'.format(unchecked_radius))

我建议您阅读Python Tutorial上的Handling Exceptions部分,其中有一个非常相似的例子。