0

我无法在互联网上找到解决这个问题的方法(也许我不够努力),但我不知道如何让输入只接受数字。我试图让输入通过一些方程式,并且每次我在输入中输入一个字母时程序都会停止。我想知道是否有办法检测输入是字母还是数字。我会展示我的程序。

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

1 回答 1

1

As suggested in the comments, you can handle a ValueError when the conversion to int fails (and save doing this same conversion throughout the rest of your code).

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

I recommend reading the Python Tutorial section on Handling Exceptions, which has a very similar example.

于 2012-12-30T12:20:29.453 回答