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

コメントで示唆されているように、への変換が失敗したときにaを処理できます (そして、コードの残りの部分全体でこの同じ変換を行うことを保存します)。ValueErrorint

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 チュートリアルセクションを読むことをお勧めします。

于 2012-12-30T12:20:29.453 に答える