#π Learning Indentation logic
25 messages Β· Page 1 of 1 (latest)
@vagrant cosmos
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.
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
indentation tells python what part of the code belongs to what block of logic
Do you have an example of code where you're unsure what needs to be indented?
β"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?"
yes exactly
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.")
How can I not be confused by distances and understand them?
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.
Are you manually typing each space or something?
practice, make mistakes, learn from them
Thanks fashoomp for the advice
Do I need to stick to one type of spacing: tap or manual?
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
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
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.