2
import calendar

def leapyr(year1, year2):
    count = 0
    while year1 <= year2:
        if calendar.isleap(year1) == True:
            count = count + 1
        year1 = year1 + 1 
    print count

leapyr(2008, 1015)

i have no bloody idea why this doesnt work. I tried "python -m tabnanny thefile.py" it tells me "indentation error: ((tokenize), line 8)" but i have no idea what to make of that information.

zvone
  • 18,045
  • 3
  • 49
  • 77
WilliamJohn
  • 113
  • 1
  • 2
  • 7

1 Answers1

4

Python allows mixing tabs and spaces. Before interpreting the source, python interpreter replaces tabs with spaces in such way that each tab is aligned to 8 spaces (see the doc on indentation).

If your editor is set to show tabs as 8 spaces, that should actually work as expected, but if it shows tabs as 4 spaces, then what it looks like is nothing like what the interpreter sees.

The code from the question is:


import calendar

def leapyr(year1, year2):

4 spacescount = 0

4 spaceswhile year1 <= year2:

tab4 spacesif calendar.isleap(year1) == True:

tabtab4 spacescount = count + 1

tabtabyear1 = year1 + 1

tabprint count

tab

leapyr(2008, 1015)


That is interpreted by Python as:

import calendar

def leapyr(year1, year2):
    count = 0
    while year1 <= year2:
            if calendar.isleap(year1) == True:
                    count = count + 1
                year1 = year1 + 1 
        print count

leapyr(2008, 1015)

This has an indentation error in line 8, at year1 = year1 + 1.

The solution is to configure the editor to always use spaces, i.e. to replace tabs with 4 spaces.

zvone
  • 18,045
  • 3
  • 49
  • 77
  • BTW, StackOverflow shows tabs as 4 spaces. I clicked *edit* on the question to get the actual source. – zvone Oct 06 '16 at 18:26
  • Note that this is specific to Python 2. Python 3 would complain immediately when it encountered mixed tabs and spaces. See e.g. https://stackoverflow.com/questions/19295519/indentation-error-with-python-3-3-when-python2-7-works-well about that. – zvone Aug 18 '18 at 14:56