私は現在 Google による python チュートリアルを行っており、ファイル list1.py を完成させています。
このdef match_ends(words)
部分に独自のコードを入力することになっています。これは、入力内の単語の数をカウントすることになっていますwords
: 2 文字以上で、最初と最後の文字が同じです。
Python 2.7 を使用して記述したコードを実行すると、正常に動作します。しかし、3.2 を使用して実行すると、そうではありません。さらに、問題があるという行を IDLE 3.2 に入力すると、問題のある行は問題なく実行されます。
これは list1.py です:
def match_ends(words):
count = 0
for x in words:
if len(x) >= 2 and x[0] == x[len(x)-1]:
count += 1
return count
def test(got, expected):
if got == expected:
prefix = ' OK '
else:
prefix = ' X '
print('%s got: %s expected: %s' % (prefix, repr(got), repr(expected)))
def main():
print('match_ends')
test(match_ends(['aba', 'xyz', 'aa', 'x', 'bbb']), 3)
test(match_ends(['', 'x', 'xy', 'xyx', 'xx']), 2)
test(match_ends(['aaa', 'be', 'abc', 'hello']), 1)
if __name__ == '__main__':
main()
Python 2.7 のコマンド ラインで実行すると、正常に動作し、次のように出力されます。
OK got: 3 expected: 3
OK got: 2 expected: 2
OK got: 1 expected: 1
Python 3.2 のコマンド ラインで実行すると、動作せず、次のように出力されます。
File "D:\Projects\Programming\Python\Tutorials\Google Python Class\google-python-exercises\basic\list1.py", line 26
if len(x) >= 2 and x[0] == x[len(x)-1]:
^
TabError: inconsistent use of tabs and spaces in indentation
最後に、IDLE 3.2 を使用すると、次のようになります。
>>> def match_ends(words):
count = 0
for x in words:
if len(x) >= 2 and x[0] == x[len(x)-1]:
count += 1
return count
>>> match_ends(["heh", "pork", "veal", "sodas"])
2
私はPythonに非常に慣れていないため、生成されるエラーのほとんどを理解するのに時間がかかりましたが、しばらくの間これに固執しています。私はそれを理解することはできません。Python 3.2 で動作せず、コマンドライン バージョンを実行した場合にのみ動作するのはなぜですか? これを修正するにはどうすればよいですか?