[Tutor] Noob: nested if-clauses

Alan Gauld alan.gauld at btinternet.com
Sun Jan 24 16:08:25 EST 2016


On 24/01/16 19:42, STF wrote:

> Let's see the following instructions:
> --------
> if condition_A:
>     instruction_1
>     instruction_2
>     if condition_B:
>       instruction_3
>       instruction_4
>     instruction_5
> else:
>     instruction_6
> --------
> 
> * How to make Pythom understand that instruction_4 is a part of condition_B
> if-clause but not a direct instruction of condition_A if-clause?  

You've done it above by the indentation.

> to make Python understand that instruction_5 is outside of condition_B
> if-clause?  Just by the number of white spaces in front of every
> instruction??

Yes, the indent level tells Python where the instruction should be.

> * How to make Python understand that "else" belongs to the first
> condition_A if-clause, not to the immediate condition_B if-clause?

Again you've done it already, just use the indent level.

> * Suppose I put four white spaces in front of instruction_1, and then "tab
> key" in front of instruction_2, would this break things?  

In Python 2 things are a wee bit flexible but in Python 3 less so.
But in general avoid mixing them, stick to spaces. Most Python
programmers set their text editor/IDE to convert tabs to
spaces(usually 4)

> most intelligent text editors would insert automatically a tab in place of
> 4 white spaces after we press Enter on a line with 4 leading white spaces.

Most can also be configured not to use tabs at all and
for Python that's better. Tell us your editor and somebody
can probably advise on optimum settings.

> * Do I really need to keep the consistency of 4 white spaces?  Not one more
> or one less?

No you can have as many or as few as you like in your own code,
just be consistent. 4 just happens to be esy to read. And its
the standard for library code so if you want to write some code
for the standard library you will need to use 4 spaces. In
the interpreter (>>>) I often only use 2 just to save typing.
But for production code I stick with 4 - not a problem since
the editor(vim) does most of the work for me.


-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos




More information about the Tutor mailing list