Python 3.x 如何只输入数字
我还没有在互联网上找到解决这个问题的方法(也许我找得不够仔细),但我不知道如何只输入数字。我试图让输入通过一些方程,每次我在输入中输入一个字母,程序就会停止。我想知道是否有办法检测输入是字母还是数字。我会展示我的节目Python 3.x 如何只输入数字,python-3.x,Python 3.x,我还没有在互联网上找到解决这个问题的方法(也许我找得不够仔细),但我不知道如何只输入数字。我试图让输入通过一些方程,每次我在输入中输入一个字母,程序就会停止。我想知道是否有办法检测输入是字母还是数字。我会展示我的节目 Radius=input("What is the radius of the circle/sphere?") Areacircle=(int(Radius)**2)*3.14159265359 Perimetercircle=2*3.141592653
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)
正如注释中所建议的,您可以在失败时进行转换(并保存在代码的其余部分执行相同的转换)
我建议阅读上的一节,其中有一个非常类似的示例。在Python中查找异常处理。您可以捕获
int()
抛出的TypeError,并使用它提供错误反馈。@Johnsyweb:ValueError-StumeyValue。。你当然是对的-P@CharlesAlleman:太好了。如果我的回答对您有帮助,请将其标记为已接受,因为这将帮助找到此页面的其他人。
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))