Yeah, sometimes I have issues with indentation as well. Alan linked a cool guide, but I'll try to share my tips as well.
- Basically we always indent things in functions that are parts of the function. Think of it as grouping everything related to this function in that function. For example if you have something like that:
Obviously this is not a well-written code, it's just an example. Basically the indent after defining the function allows you to tell the computer that everything that is indented is a part of this function. Now, why is that important? Well, if you put that
return command without the indentation, the computer is gonna think that you want to return a thing from outside the function. Now, this sometimes makes sense if the code is bigger and there are more than one function, and sometimes you want to return things outside of the functions.
- Now, you want to do indentation thing inside the function as well. You basically always indent after giving an if command, because it tells the computer that something happens specifically after this very specific condition is fulfilled. It also allows you to put multiple ifs and still know, which conditions are tied to which results, like that:
Now, as you see, indentation allows you to see instantly what is the structure of given code. So yeah, it is worth to learn how to do it, because it will make your work easier so much.
Now, a lot of my troubles concerning indentation come from the fact that sometimes the code gets a bit messed up in the editor and sometimes in one place you have four spaces and in second place you indent with tab key. Different editors interprete it in different ways so you need to be really consistent with that.
Overall Python is a lot about being consistent. It is hard, yeah, but once you get used to that, it's getting pretty easy and if you move to another programming language, you'll appreciate how easy-looking is Python code