2017-03-21 4 views
0

私は単純な平方根計算機を作りたがっていました。Python Square Root Calculator Error

num = input('Enter a number and hit enter: ') 

if len(num) > 0 and num.isdigit(): 
    new = (num**0.5) 
    print(new) 
else: 
    print('You did not enter a valid number.') 
私は何も悪いことをしたかのように思われない

、しかし、私はプログラムを実行しようと、私は番号の入力を持っていた後、私は次のエラーメッセージに直面していたとき:

Traceback (most recent call last): 
File "/Users/username/Documents/Coding/squareroot.py", line 4, in <module> 
new = (num**0.5) 
TypeError: unsupported operand type(s) for ** or pow(): 'str' and 'float' 

Process finished with exit code 1 
+1

入力は* *数に変換することができれば、あなたは慎重に*その後*実際にそれを行うには気にしないでください、確認してください! – jonrsharpe

+0

また、「1.5」や「1E10」のような数字は有効ではありません - なぜですか? pythonの方法は、入力を 'float'に変換しようと試みることと、例外が発生したときだけエラーメッセージを出力することです。 –

+0

[TypeError: - : 'str'と 'int'のサポートされていないオペランドタイプの重複可能性](http://stackoverflow.com/questions/2376464/typeerror-unsupported-operand-types-for-str-and) -int) –

答えて

3

あなたはこのソリューションを使用することができ、それを解析する必要があります。ここでtryとcatchはあらゆる種類の入力を処理できます。あなたのプログラムは決して失敗しません。入力がfloatに変換されているためです。どんなタイプのエラーにも直面しません。

try: 
    num = float(input('Enter a positive number and hit enter: ')) 
    if num >= 0: 
     new = (num**0.5) 
    print(new) 

except: 
    print('You did not enter a valid number.') 
0

入力関数は文字列値を返します。あなたは適切

num = raw_input('Enter a number and hit enter: ') 

if num.isdigit(): 
    if int(num) > 0: 
     new = (int(num)**0.5) 
     print(new) 
else: 
    print('You did not enter a valid number.') 
+0

その後、2行目が失敗します。 –

+0

うーん、私はそれを試して、それはそのエラーを排除した。ただし、別のエラーメッセージが表示されます: トレースバック(最新のコール最後): ファイル「/Users/username/Documents/Coding/squareroot.py」3行目 len(num)> 0の場合num.isdigit(): TypeError: 'int'型のオブジェクトにlen()がありません – PythonPie

+0

@ShivkumarKondi私の答えとあなたの違いは何ですか? – eyllanesc

0

簡単な計算には数学モジュールを使用します。 参照してください:Math module Documentation.

import math 
num = raw_input('Enter a number and hit enter: ') 

if num.isdigit(): 
    num = float(num) 
    new = math.sqrt(num) 
    print(new) 
else: 
    print('You did not enter a valid number.')