#πŸ”’ Learning Indentation logic

25 messages Β· Page 1 of 1 (latest)

vagrant cosmos
#

I am a beginner and I want to understand the logic of Indentation in Python.
When should I use 4 spaces and when should I return to the start of the line?
Thank you!

distant iceBOT
#

@vagrant cosmos

Python help channel opened

Remember to:

  • Ask your Python question, not if you can ask or if there's an expert who can help.
  • Show a code sample as text (rather than a screenshot) and the error message, if you've got one.
  • Explain what you expect to happen and what actually happens.

:warning: Do not pip install anything that isn't related to your question, especially if asked to over DMs.

undone wind
#

you indent after you type a :

#

after the block ends, you unindent

#

so if you have an if statement,

if is_raining:
  print("it is raining")
print("it is what it is")

the indented code only runs if the condition is true. code that isn't indented is always run

delicate matrix
#

Do you have an example of code where you're unsure what needs to be indented?

vagrant cosmos
#

​"Does this mean I can put an 'if' inside another 'if'? Like a child of a child? And should I use more spaces (like 8 spaces) for the second one?"

delicate matrix
#

I don't think of it as "8 spaces". I think of it as "4 more than the previous"

#
if name == 'bob':
    if favourite_colour == 'blue':
        print("I like you.")
vagrant cosmos
#

How can I not be confused by distances and understand them?

wraith hedge
# vagrant cosmos ​"Does this mean I can put an 'if' inside another 'if'? Like a child of a child?...

You need extra indent for each level of nesting. It doesn't need to be 4 additional spaces; that is just the common convention. At least one extra space.

Everything in a particular indent block has to be indented the same amount.

Legal:

if something:
  if someotherthing:
      print(1)
  else:
    print(2)
    print(3)

This is legal - the print(2) and print(3) need to have the same indent, but it does not need to be the same as the print(1).

But most people use the same amount of indent for each additional indent, and that amount is usually 4.

graceful olive
delicate matrix
vagrant cosmos
#

Thanks fashoomp for the advice

#

Do I need to stick to one type of spacing: tap or manual?

graceful olive
#

If you use a decent programming text editor, then pressing tab in a Python file will insert 4 spaces

#

You do not have to, and should not, manually type in 4 spaces one by one

vagrant cosmos
#

Use the PyCharm text editor

#

Thank you all for the help! This was a great first experience for me. I understand the logic now!"

#

close!

#

!close

distant iceBOT
#
Python help channel closed with !close

This help channel has been closed. Feel free to create a new post in #1035199133436354600. To maximize your chances of getting a response, check out this guide on asking good questions.