How does indentation work exactly?. Could someone expand on the explantion given on that page please.

-regards.

Recommended Answers

All 18 Replies

It's very simple, some idioms in a python program introduce a *block* of statements. The block of statements must be non empty and indented. They are introduced by lines ending with a : . These idioms are

# class definitions
class myClass(object):
    # block of statements (indented)

# function definitions
def myFunction(*args, **kwd):
    # block of statement (indented)

# if statements
if myCondition:
    # block of statements
elif condition:
    # block of statements
else:
    # block of statements

# while loops
while condition:
    # block of satements

# for loops
for x, y in coordinates:
    # block of statements

# try .. except clauses
try:
    # block of statements
except myException:
    # block of statements
finally:
    # block of statements

# with statements (advanced)
with expression as variable:
    # block of statements

Roughly speaking, each time you end a line with a colon (outside a literal dictionary definition), you must write an indented block after this line. If you need an empty block, put the pass statement as the only statement of the block.
Blocks can be nested of course:

while condition1:
    print("hello") # indented
    while inner_condition:
        print("hi") #inner block indented twice

The recommended and most widely used way to indent is to put 4 spaces for each indentation, but you're free to put any number of spaces you want (I like 2 spaces). However the indentation must be coherent in the same file. You cannot indent with 4 spaces at the beginning of the file and with 2 spaces at the end of the file. Tab characters can be used to indent, but from my experience, they should be avoided. Most editors support converting tab key hits into spaces.

from my experience, they should be avoided. Most editors support converting tab key hits into spaces.

I use one tab or four spaces
They give me no problem, so I guess:
1Tab = 4spaces

No, it's probably because your editor writes 4 spaces when you hit the tab key. Read your pyhon file as a string, and print it's repr, you'll see if it actually contains tab characters.

As I understand it, Python couldn't care less how many spaces / tabs you use other than requiring that all lines within a block must have the same amount of whitespace.

Any statements you have which start a new block (see above in this thread) require that the new block has more whitespace than the statement which introduced it.

That being said, although it would be legal to indent your first block 1 space, your second 8 more, and your third 3 more (etc., randomizing at will) it would make your code much harder to read.

I'm firmly in the 4 spaces camp. I do like the look, but the first selection of 4 was because it was the editor default.

I use one tab or four spaces
They give me no problem, so I guess:
1Tab = 4spaces

You may not have a problem with your tabs and your tab setting, but I have run into plenty of problems with other folks' code that have used tabs. Please avoid tabs!

I use one tab or four spaces
They give me no problem, so I guess:
1Tab = 4spaces

I think Ene is right here, please don't use tabs for indentations, they are bound to mix with spaces!

I actually noticed one of evstevemd's wxPython code samples that I copied and pasted into my PSPad editor. It came through like that ...

import wx

class Frame1(wx.Frame):
    def __init__ (self, parent, id, title):
        wx.Frame.__init__(self, parent, id, title, size=(400, 400))
  self.text = wx.TextCtrl(self, -1, style = wx.TE_MULTILINE)

  x = dir(wx)

  for y in x:
      if y.find('ID_')!=-1:
    search = y + "\n"
    self.text.write(search)


app = wx.App(False)
f = Frame1(None, -1, "wx.IDs")
f.Centre()
f.Show(True)
app.MainLoop()

Almost unusable!

You can sort of figure out where tabs where used and where spaces were used.

ok so, just practising here sorry for useless console app but why not use {} to separate blocks.

number = 2
guess = 2

if number == guess:
print ('yep its identicle')

when i run that it says indentation error, but when i do

number = 2
guess = 2

if number == guess: {
print ('yep its identicle') }

is indentation the preferred and standard method when writing python code?

Why not use braces to separate blocks ? because you're not writing C but python code and this use of braces doesn't belong to the syntax of python. Indentation is the only way to express the block structure in python. Braces only appear in the definition of literal dictionary objects.

Indentation was done on purpose, and is one of Python's features that makes its syntax more readable. Yes it forces the programmer to use proper indentation, something that is often not done in code written in C. I have seen 300 line C code where every line starts at column 1. Go to the C forum and see how many times people, trying to help, request indentation.

Here is an example of what C will let you get away with:

// example of badly written C code, it works!

#include <stdio.h>
#include <string.h>

int bin2dec(char *bin);

int main(){char bin[80]="";char *p;  int  dec;
while(strcmp(bin,"0")){printf("\n Enter binary number (0 only exits): ");
fgets(bin, sizeof(bin), stdin);if ((p = strchr(bin,'\n')) != NULL){
*p = '\0';}dec=bin2dec(bin);if (dec)
printf("\nDecimal = %d  Hexadecimal = 0x%04X  Octal = 0%o\n",dec,dec,dec);
}getchar();return 0;}int bin2dec(char *bin){int b, k, m, n;
int  len, sum = 0;len = strlen(bin) - 1;for(k = 0; k <= len; k++){
n = (bin[k] - '0');if ((n > 1) || (n < 0)){
puts("\n\n ERROR! BINARY has only 1 and 0!\n");return (0);}
for(b = 1, m = len; m > k; m--){b *= 2;}sum = sum + n * b;}return(sum);}

If your block is only one statement, then you can do something like this:

number = 2
guess = 2

if number == guess: print("yep it's identical")

If your block is only one statement, then you can do something like this:

if number == guess: print("yep it's identical")

It's true, but G Van Rossum regrets this, so I wouldn't say it's good python code.

commented: Good point! +11

If you are averse to indentations, you may want to give Ruby a try. Here is a Ruby code sample with indentations ...

# example of ruby code
# calculate Fibonacci(20)

def fib(n)
  if n<2
    n
  else
    fib(n-2)+fib(n-1)
  end
end
print(fib(20), "\n")

This one works equally well, but is less readable ...

# example of ruby code, no indentations
# calculate Fibonacci(20)

def fib(n)
if n<2
n
else
fib(n-2)+fib(n-1)
end
end
print(fib(20), "\n")

It's true, but G Van Rossum regrets this, so I wouldn't say it's good python code.

I agree. I have seen code that uses this possibility, particularly when it's just a simple return statement. It really stops clarity, so I don't use it.

You may not have a problem with your tabs and your tab setting, but I have run into plenty of problems with other folks' code that have used tabs. Please avoid tabs!

Noted!
I'll convert all my codes to spaces with my Wing IDE
Thanks for that

ok so, just practising here sorry for useless console app but why not use {} to separate blocks.

number = 2
guess = 2

if number == guess:
print ('yep its identicle')

when i run that it says indentation error, but when i do

number = 2
guess = 2

if number == guess: {
print ('yep its identicle') }

is indentation the preferred and standard method when writing python code?

There are many code editors out there that cater to Python and do the proper indentation for you after you type a statement with a colon.

There are many code editors out there that cater to Python and do the proper indentation for you after you type a statement with a colon.

I have been afraid of Vim editor, due to NO-knowledge. But today I found a nice book from Swaroop C.H.
I will go back and practice it. So I suggest for anyone intereseted to check the link. Big blow to Emacs guys (I found them always debating which is the best. I hope this will credit more vim guys) :)

http://www.swaroopch.com/notes/Vim

>I have been afraid of Vim editor, due to NO-knowledge.
Practice will change that. Learn as you go according to your need. Vim has much to offer, but until you start using it, you'll will not know what it is applicable to you in your way of writing.
Thanks for the link.

I had been using vim for simple text editing of small files, but I didn't ever try to use it for programming. Then the other day I saw that book by Swaroop. From that book I learned how to customize my .vimrc file to do file detection, smart indenting, use spaces instead of tabs, and show me line numbers. Now I am programming with vim and loving it! Thanks Swaroop!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.