vb.net – Python: Where does if-endif-statement end?

vb.net – Python: Where does if-endif-statement end?

Yes. Python uses indentation to mark blocks. Both the if and the for end there.

In Python, where your indented block ends, that is exactly where your block will end. So, for example, consider a bit simpler code:

myName = Jhon
if myName == Jhon:
   print(myName * 5)
else:
   print(Hello)

Now, when you run this code (make sure to run it from a separate module, not from the interactive prompt), it will print Jhon five times (note that Python will treat the objects exactly as they are specified, it wont even bother to try to convert the variable myNames value to a number for multiplication) and thats it. This is because the code block inside of the if block is only executed. Note that if the else keyword was put anywhere but just below the if statement or if you had mixed the use of tabs and spaces, Python would raise an error.

Now, in your code,

for i in range(0,numClass):
    if breaks[i] == 0:
       classStart = 0
    else:
       classStart = dataList.index(breaks[i])
       classStart += 1

See, where the indent of fors block of code starts? One tab, so, everything indented one tab after the for statement, will be inside of the for block. Now, obviously, the if statement is inside of the for statement, so its inside the for statement. Now, lets move to next line, classStart = 0 — this is indented two tabs from the for statement and one tab from the if statement; so its inside the if statement and inside the for block. Next line, you have an else keyword indented just one tab from the for statement but not two tabs, so its inside the for statement, and not inside the if statement.

Consider putting curly-braces like these if you have coded in another language(s) before:

for i in range(0,numClass)
{
    if breaks[i] == 0
        {
        classStart = 0
        }
    else
        {
        classStart = dataList.index(breaks[i])
        classStart += 1
        }
}

The simple differences are that you are not required to put parenthesis for your expressions, unless, you want to force operator precedence rule and you dont need those curly braces, instead, just indent them equally.

vb.net – Python: Where does if-endif-statement end?

That is right. In Python, the indentation delimitates your condition block, differently from e.g., Matlab, where you would have to insert an end to mark the blocks end. I like both ways though!

Leave a Reply

Your email address will not be published. Required fields are marked *