私は文字通り今週Pythonを学び始めました。(私は1か月でコンピュータサイエンスを新しくします!)
これは、xの平方根を計算するために作成した関数です。
#square root function
def sqrt(x):
"""Returns the square root of x if x is a perfect square.
Prints an error message and returns none if otherwise."""
ans = 0
if x>=0:
while ans*ans <x:
ans = ans + 1
if ans*ans == x:
print(x, 'is a perfect square.')
return ans
else:
print(x, 'is not a perfect square.')
return None
else: print(x, 'is a negative number.')
しかし、それを保存してPythonシェルにsqrt(16)と入力すると、エラーメッセージが表示されます。
NameError: name 'sqrt' is not defined
Python3.1.1を使用しています。私のコードに何か問題がありますか?どんな助けでもいただければ幸いです。ありがとう
更新 さて、皆さんのおかげで、関数をインポートしていないことに気づきました。また、インポートしようとすると、C:\Python31ではなく汎用のマイドキュメントファイルに保存したため、エラーが発生しました。したがって、スクリプトをC:\ Python31 \ squareroot.pyとして保存した後、シェルに入力しました(再起動しました)。
平方根をインポートする
そして、新しいエラーが発生しました!
>>> import squareroot
Traceback (most recent call last):
File "<pyshell#0>", line 1, in <module>
import squareroot
File "C:\Python31\squareroot.py", line 13
return ans
SyntaxError: 'return' outside function
私の元のコードにバグがあったことを意味します!私は今、以下の提案された修正のいくつかを見るつもりです。他に何か見つけた場合は、言ってください。ありがとう :)
更新2-それはうまくいった!!!!!!!!!!
これが私がしたことです。まず、IamChuckBから親切に投稿されたクリーンアップされたバージョンのコードを使用しました。これを含む新しいスクリプトを作成しました(区別するために関数名をsqrtからsqrtaに変更しました)。
def sqrta(x):
"""Returns the square root of x if x is a perfect square.
Prints an error message and returns none if otherwise."""
ans = 0
if x>=0:
while ans*ans <x:
ans = ans + 1
if ans*ans == x:
print(x, 'is a perfect square.')
return ans
else:
print(x, 'is not a perfect square.')
return None
else:
print(x, 'is a negative number.')
そして、重要なことに、それをC:\ Python31 \ squareroota.pyとして保存しました(ここでも、この他の失敗したファイルを区別するために、最後に「a」を追加しました)。
次に、Pythonシェルを再度開いて、次のことを行いました。
>>> import squareroota
何も起こらなかった、エラーもなかった、素晴らしい!それから私はこれをしました:
>>> squareroota.sqrta(16)
そしてこれを手に入れました!
16 is a perfect square.
4
わお。これは学校でABCブロックで遊んでいるように見えるかもしれませんが、正直なところ私は心を打たれました。みなさん、ありがとうございました!