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 won't even bother to try to convert the variable myName
's value to a number for multiplication) and that's 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 for
's 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 it's inside the for
statement. Now, let's move to next line, classStart = 0
-- this is indented two tabs from the for
statement and one tab from the if
statement; so it's 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 it's 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 don't need those curly braces, instead, just indent them equally.