Python Forum
Thread Rating:
  • 1 Vote(s) - 1 Average
  • 1
  • 2
  • 3
  • 4
  • 5
indentation tips
#1
I am not a programmer, that is easy to see. I have a lot of trouble with the indentation. I write little routines using the idle3 environment. I just got this working, to put photos in an excel file.

Idle3 is set to 4 spaces = 1 tab, but when I press tab, I often seem to get more than 4 spaces. This below works for me on my computer, in the idle3 shell and in a terminal. If I change it at all, my little routine does not run, or does not do what I want.

If you have a link to some advice on indentation, I would like to read it! Thanks!

for sheet in sheets:
	activeDirectory = pathToPhotos + sheet + '/'
	print('the active photo directory is ' + activeDirectory)
	for filename in os.listdir(activeDirectory):
			if not (filename.endswith('.jpg')):
				continue
			for rowNum in range(beginRow, wb[sheet].max_row + 1):
				getName = filename.split('.')
				if (getName[0] == wb[sheet].cell(row=rowNum, column=col).value):
					print('found the name! Name is: %s ' % (getName[0]))
					print('Putting pic in row ' + str(rowNum))
					img = Image(activeDirectory + filename)
					wb[sheet].add_image(img, 'A' + str(rowNum))
Reply
#2
If you copied the file from somewhere else, the original code may contain hard tabs that you cannot see. Supposing the program is named 'myprogram.py', you can do the following
  • Close IDLE and open a terminal (or cmd window depending on your OS)
  • Type the command python -m pip install reindent and press return
  • Navigate to the directory/folder containing 'myprogram.py'
  • Type the command reindent myprogram.py and press return
  • Close the terminal and open the file with IDLE again.
Reply
#3
I'd say there are two different issues here:
  • the mechanics of inserting/fixing indents
  • understanding how indents work with respect to flow of execution

You've already been given links/advice on how to re-ident code and configure IDLE.

The PEP8 guide on Python formatting and style says to stick with spaces and there should be four spaces per indentation level. Code you copy from elsewhere may not follow either of these conventions but you can configure your editor to fix these for you.

With respect to understanding indentation, I wrote a simple overview for a different forum. This may be too basic for you, but I share it here in case it is of any help.

Indentation is about belonging.

Consider it an hierarchy. Think of how a family tree works (thinking about the bloodline only). Each child (an indent) can have children (another indent). Children of the same parent are indented the same amount.

In code, there are many statements (code) that mean something should be done only if a certain condition is met.

In English, consider:

If it is raining then put on your coat, hat, gloves and wellingtons otherwise just put on your shoes.

Each of the actions:
  • put on coat
  • put on hat
  • put on wellingtons
  • put on gloves (last thing to do logically)
are all part of what you do if it is raining.

In pseudo code:

weather = weather_api(my_location)
if weather == "raining":
    put_on_coat()
    put_on_hat()
    put_on_wellingtons()
    put_on_gloves()
else:
    put_on_shoes()
go_shopping() 
There are lots of places in Python that this indenting of a block of code is used to indicate belonging.

That code above could have had additional conditions within the indented blocks.

Maybe checking the temperature and putting on a warmer coat if cold:

weather, temperature = weather_api(my_location)
if weather == "raining":
    if temperature == "cold":
        put_on_jumper()
        put_on_winter_coat()
        put_on_scarf()
    else:
        put_on_rain_coat()
    put_on_hat()
    put_on_wellingtons()
    put_on_gloves()
else:
    put_on_shoes()
go_shopping()
I am trying to help you, really, even if it doesn't always seem that way
Reply
#4
Thanks, I will have to try to keep everything simple, break things down into smaller steps. I had a problem with putting an 'if clause' in my calculate % scores routine. I could not get the indentation to work, so I put this before that step:

# avoid None values in any relevant cells
for sheet in sourceSheetNames:
	sourceFileActiveSheet = sourceFile[sheet]
	maxCol = sourceFileActiveSheet.max_column
	maxRow = sourceFileActiveSheet.max_row
	for colNum in range(11, maxCol + 1, 3):
	    for rowNum in range(4, maxRow +1):
		    if sourceFileActiveSheet.cell(row=rowNum, column=colNum).value == None:
			    sourceFileActiveSheet.cell(row=rowNum, column=colNum, value=0)
This avoids any errors like this

Quote:Traceback (most recent call last):
File "./calculate%scores.py", line 98, in <module>
totalAttendance = totalAttendance + addScore
TypeError: unsupported operand type(s) for +: 'int' and 'NoneType'
Reply
#5
You could also try a conversion such as
def znone(x):
    return 0 if x is None else x

totalAttendance = znone(totalAttendance) + znone(addScore)
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Any tips to how to find out values? nevlindan 1 687 Apr-27-2023, 09:14 PM
Last Post: deanhystad
  coding improvement tips vaisesumit29 1 1,773 Mar-10-2019, 05:09 PM
Last Post: stullis
  Tips for CLI program with Keybinding system pedropessoa 2 2,546 Nov-21-2018, 09:59 AM
Last Post: Gribouillis
  Organizing tips Demini 1 2,185 Feb-10-2018, 05:32 AM
Last Post: metulburr

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020