简体   繁体   中英

Python code compiles in 2.7, not in 3.2

I am doing the python tutorial by Google right now, and am completing the file list1.py.

I am supposed to fill in the def match_ends(words) part with my own code, which is supposed to count how many words in the input words have both: more than 2 letters and the same beginning and ending letters.

When I run the code I wrote using python 2.7, it works fine. But when I run it using 3.2, it doesn't. Further, when I type the line that it says has a problem into IDLE 3.2, the troublesome line runs fine.

This is 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()

When I run it in command line for Python 2.7, it works fine, outputs:

 OK  got: 3 expected: 3
 OK  got: 2 expected: 2
 OK  got: 1 expected: 1

When I run it in command line for Python 3.2, it doesn't work, outputs:

  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

Finally, when I use IDLE 3.2, I get:

>>> 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

I'm extremely new to Python, most of the errors that are generated have taken some time to figure out, but I've been stuck on this one for awhile. I can't figure it out. Why won't it work in Python 3.2, and only when I do the command-line version? How do I fix this?

You're probably mixing tabs and spaces characters, which is not allowed anymore in Python 3.x. You can fix this by displaying whitespaces characters within your text editor.

Indentation is rejected as inconsistent if a source file mixes tabs and spaces in a way that makes the meaning dependent on the worth of a tab in spaces; a TabError is raised in that case.

Quoted from: http://docs.python.org/py3k/reference/lexical_analysis.html#indentation

Your third line starts with two spaces, while the fourth starts with a single tab. I'm guessing Python 2 is more forgiving of inconsistencies than Python 3.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM