Little question about Python logic


#1

Hello All,
I'm just extremely curious about how Python works with the space in front of lines. By my testing below,

correct one:
for number in start_list :
(4 spaces)square_list.append(number**2)

wrong one:
for number in start_list :
square_list.append(number**2)

Could anyone explain easily how the logic works behind it for me?
Thanks a lot


#2

uhm... how can you have progressed so far without releasing the important of indention in pyton? Python uses indention to determine what is nested inside a function, if/elif/else, for loop statements.

javascript for example uses curly brackets:

for(var i =0;i<5;i++){
    console.log(i);
}

#3

Python Style Guide discusses good indentation style.


#4

In python, there isn't a command to end a for/while/if etc. statement. In some languages you might define the code to be used within the statement with {}, or by initiating (if) and closing off (endif) a statement.
In python you just use indentation to show what's included in a statement.

For example,

for i in range (0, 3):
   print(i)
   print('mark')

will result in:

0
mark
1
mark
2
mark

while

for i in range (0, 3):
   print(i)

print('mark')

will result in:

0
1
2
mark

To my knowledge, indenting code after a statement that is not an if/while/for/def statement (e.g. a statement not followed by a : ) will result in error, and doing this is not necessary anyway.

Also, when coding (although it doesn't seem to work in the comments) using the tab key is a faster way to achieve indentation, as it is the same length as 4 spaces.


#5

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.