Nested structures and indentation in Python

  • Context: Python 
  • Thread starter Thread starter fog37
  • Start date Start date
  • Tags Tags
    Python Structures
Click For Summary

Discussion Overview

The discussion revolves around the importance of indentation in Python programming, particularly in the context of nested structures such as loops and conditional statements. Participants explore how indentation affects code interpretation and the structure of blocks in Python.

Discussion Character

  • Exploratory
  • Technical explanation
  • Debate/contested
  • Mathematical reasoning

Main Points Raised

  • Some participants assert that indentation is mandatory in Python and that blocks of code are defined by their indentation levels.
  • Others clarify that code without indentation is considered module-level code and not part of any block.
  • There is a discussion about whether an if-statement is considered nested if it is indented relative to a preceding loop.
  • Some participants express confusion about the necessity of certain lines of code, questioning if they are redundant due to previous logic.
  • Several participants request code examples to better understand the issues being discussed, emphasizing the importance of proper formatting.
  • Concerns are raised about potential syntax errors resulting from improper indentation.

Areas of Agreement / Disagreement

Participants generally agree on the significance of indentation in defining code blocks, but there are multiple competing views regarding the necessity of certain lines of code and the interpretation of nested structures. The discussion remains unresolved on these points.

Contextual Notes

Some participants mention specific errors related to indentation, but there is no consensus on the necessity of certain lines of code or the implications of removing indentation.

fog37
Messages
1,566
Reaction score
108
TL;DR
indentation and nested structures
Hello!

In the context of Python, indentation is very important and mandatory. The entire code is separated into blocks and each block has its own indentation. Two blocks with the same indentation belong are the same block unless the blocks are separated by a block with less indentation, correct?

Nested loops (for or while) and nested if statements (can we talk about nested if-statements?) are considered nested by the interpreter if they have indented relative to the structure they are nested in, correct? Without the indentation, what are they considered? I wrote a block of code that was not meant to be nested but was interpreted as nested because the block was indented.

Thank you!
 
Technology news on Phys.org
fog37 said:
The entire code is separated into blocks

Not quite. Code that isn't indented at all isn't in any block; it's module level code.

fog37 said:
Two blocks with the same indentation belong are the same bloc

If you have a series of lines of code with the same indentation, they're not two blocks, they're one block.

I would suggest posting actual code examples of what you're describing.

fog37 said:
Nested loops (for or while) and nested if statements (can we talk about nested if-statements?) are considered nested by the interpreter if they have indented relative to the structure they are nested in, correct?

As far as constructing the syntax tree of the code, all of these things are just blocks. The tree structure doesn't care about the specific kind of block, just that it's a block. Blocks can of course be nested.

fog37 said:
Without the indentation, what are they considered?

I don't understand what you mean. Again, actual code examples would help a lot.

fog37 said:
I wrote a block of code that was not meant to be nested but was interpreted as nested because the block was indented.

Unless you post the code here, we can't possibly tell what happened with it.
 
  • Like
Likes   Reactions: fog37
fog37 said:
Without the indentation, what are they considered?
For a single statement, you can write it on the same line, beside the if condition. As soon as you put a new line, you need to indent. Anything else is a syntax error.
fog37 said:
I wrote a block of code that was not meant to be nested but was interpreted as nested because the block was indented.
I would like to see that code too. Because I tend to get the error 'unexpected indent', if indentation is not appropriately used.
 
  • Like
Likes   Reactions: fog37
Thank you everybody. Here the code sample:
*****************************************************
text = 'Today is Friday'
letter = input('Enter a letter to search in the string called "test" above:')
found = False # the variable found is Boolean type and set to False initially
# The for loop below scans through the string "text" to find the letter provided by the user
for x in text :
if x == letter :
found = True
break
# Is the if statement above ( if x==letter :) a nested if-statement because of the indentation after the for loop? What would happen if I removed the indentation?
# Why is the next line (if found == True) of code needed? It does not seem necessary to me...
if found == True :
print("Letter", letter, "found!")
*****************************************************
 
fog37 said:
Thank you everybody. Here the code sample:
*****************************************************
text = 'Today is Friday'
letter = input('Enter a letter to search in the string called "test" above:')
found = False # the variable found is Boolean type and set to False initially
# The for loop below scans through the string "text" to find the letter provided by the user
for x in text :
if x == letter :
found = True
break
# Is the if statement above ( if x==letter :) a nested if-statement because of the indentation after the for loop? What would happen if I removed the indentation?
# Why is the next line (if found == True) of code needed? It does not seem necessary to me...
if found == True :
print("Letter", letter, "found!")
*****************************************************
You need to repost this with "Code" tags. See the "</>" symbol in the line at the top of the post? That will preserve the code formatting, including the indenting.
 
  • Like
Likes   Reactions: fog37
[CODE title="Search for letter in the text" highlight=""6,11""]text = 'Today is Friday'
letter = input('Enter a letter to search in the string called "text" above:')
found = False # the variable found is Boolean type and set to False initially
# The for loop below scans through the string "text" to find the letter provided by the user
for x in text :
if x == letter :
found = True
break
# Is the if-statement on line 6 a nested if-statement because of the indentation after the for loop? What would happen if I removed the indentation?
# Why is the next line (if found == True) of code needed? It does not seem necessary to me...
if found == True :
print("Letter", letter, "found!")[/CODE]

Thank you.
 
I don't see indentation in your code (You should use the 'Code' tag; the button with '</>' ).

I'm guessing your code should look like this:
Python:
text = 'Today is Friday'
letter = input('Enter a letter to search in the string called "test" above:')
found = False # the variable found is Boolean type and set to False initially
# The for loop below scans through the string "text" to find the letter provided by the user
for x in text :
    if x == letter :
        found = True
        break

# Is the if statement above ( if x==letter :) a nested if-statement because of the indentation after the for loop? What would happen if I removed the indentation?
# Why is the next line (if found == True) of code needed? It does not seem necessary to me...
if found == True :
print("Letter", letter, "found!")
found is set to true only if one x == letter.
 
  • Like
Likes   Reactions: fog37
This doesn't show any indenting. Here's how it should look:
Python:
text = 'Today is Friday'
letter = input('Enter a letter to search in the string called "test" above:')
found = False # the variable found is Boolean type and set to False initially
# The for loop below scans through the string "text" to find the letter provided by the user
for x in text :
    if x == letter :
        found = True
        break
# Is the if statement above ( if x==letter :) a nested if-statement because of the indentation after the for loop? What would happen if I removed the indentation?
# Why is the next line (if found == True) of code needed? It does not seem necessary to me...
if found == True :
    print("Letter", letter, "found!")

The last if statement is needed, because it is possible that the for loop wen through all of the letters without finding any x that matched letter.
 
  • Like
Likes   Reactions: jack action
Also, without the indentation, you will get a compilation error.
 
  • Like
Likes   Reactions: jack action
  • #10
jack action said:
I don't see indentation in your code (You should use the 'Code' tag; the button with '</>' ).

I'm guessing your code should look like this:
Python:
text = 'Today is Friday'
letter = input('Enter a letter to search in the string called "test" above:')
found = False # the variable found is Boolean type and set to False initially
# The for loop below scans through the string "text" to find the letter provided by the user
for x in text :
    if x == letter :
        found = True
        break

# Is the if statement above ( if x==letter :) a nested if-statement because of the indentation after the for loop? What would happen if I removed the indentation?
# Why is the next line (if found == True) of code needed? It does not seem necessary to me...
if found == True :
print("Letter", letter, "found!")
found is set to true only if one x == letter.
Hi, that is correct about the indentation...

I guess I wondering:

a) is line #12, found == True, really needed for the code to work properly? It seems to be already taken care in line # 7.
b) does the indentation for if letter == True makes the if-statement a nested if-statement?
 
  • #11
fog37 said:
Hi, that is correct about the indentation...

I guess I wondering:

a) is line #12, found == True, really needed for the code to work properly? It seems to be already taken care in line # 7.
Yes, that line is really needed. Line #7 is only executed if the code actually finds an x that equals letter. If it doesn't it will go all the way through the for loop and finish the for loop with found still equal to False.

b) does the indentation for if letter == True makes the if-statement a nested if-statement?
The if statement is nested within the loop. It is not nested within another if statement. Is that clear?
 
  • Like
Likes   Reactions: fog37
  • #12
jack action said:
I don't see indentation in your code (You should use the 'Code' tag; the button with '</>' ).

I'm guessing your code should look like this:
Python:
text = 'Today is Friday'
letter = input('Enter a letter to search in the string called "test" above:')
found = False # the variable found is Boolean type and set to False initially
# The for loop below scans through the string "text" to find the letter provided by the user
for x in text :
    if x == letter :
        found = True
        break

# Is the if statement above ( if x==letter :) a nested if-statement because of the indentation after the for loop? What would happen if I removed the indentation?
# Why is the next line (if found == True) of code needed? It does not seem necessary to me...
if found == True :
print("Letter", letter, "found!")
found is set to true only if one x == letter.

Note that this still isn't correct. The last line (print("Letter", letter, "found!")) needs to be indented as well.
 
  • Like
Likes   Reactions: jack action and fog37
  • #13
phyzguy said:
Note that this still isn't correct. The last line (print("Letter", letter, "found!")) needs to be indented as well.

Couldn't we eliminate the last portion of the code and bring the print statement into the for loop:

[CODE highlight="8"]text = 'Today is Friday'
letter = input('Enter a letter to search in the string called "test" above:')
found = False

for x in text :
if x == letter :
found = True
print("Letter", letter, "found!")
break[/CODE]
 
  • #14
jack action said:
I don't see indentation in your code (You should use the 'Code' tag; the button with '</>' ).

I'm guessing your code should look like this:
Python:
text = 'Today is Friday'
letter = input('Enter a letter to search in the string called "test" above:')
found = False # the variable found is Boolean type and set to False initially
# The for loop below scans through the string "text" to find the letter provided by the user
for x in text :
    if x == letter :
        found = True
        break

# Is the if statement above ( if x==letter :) a nested if-statement because of the indentation after the for loop? What would happen if I removed the indentation?
# Why is the next line (if found == True) of code needed? It does not seem necessary to me...
if found == True :
print("Letter", letter, "found!")
found is set to true only if one x == letter.

In the figure below, as far as indentation, the red statements are all in the same block (block 1). Block 2 and block 3 are different blocks even if they have the same indentation. They are both part of block 1.

Fundamentally, what does it mean for certain statement to be inside the same block? It is not about what gets executed first or after other statements, I think. I get that lines of code in the same block "go together" but I am not completely sure what that really means.

1599245579845.png


In this next example, the situation is different:

1599245799076.png
 
  • #15
[Note that I conquer that I made an error in my previous post and the last line do need an indentation.]
fog37 said:
Couldn't we eliminate the last portion of the code and bring the print statement into the for loop:

[CODE highlight="8"]text = 'Today is Friday'
letter = input('Enter a letter to search in the string called "test" above:')
found = False

for x in text :
if x == letter :
found = True
print("Letter", letter, "found!")
break[/CODE]
Yes, you can do that. In such a case, you don't even need the variable found at all.
 
  • Like
Likes   Reactions: fog37
  • #16
I'm not sure why you are so intent on the concept of a block. You might try reading the Wiki entry. But Python is a bit more lax about what happens inside of code blocks than some other languages like C or C++. Look what happens in these two cases. In Python:
Python:
mult = 0
print("Before the loop. mult = ", mult)
for i in range(5):
    mult = i * 5
    print("In the loop. mult = ", mult)
print("Loop finished. mult = ", mult)
When you run this code, it prints out:
Before the loop. mult = 0
In the loop. mult = 0
In the loop. mult = 5
In the loop. mult = 10
In the loop. mult = 15
In the loop. mult = 20
Loop finished. mult = 20

But a similar C++ code:
C++:
#include <iostream>

int main ()
{
    int mult = 0;
    std::count << "Before the loop. mult = " << mult << "\n";
    for (int i = 0; i < 5; i++)
      {
    int mult = i * 5;
    std::count << "In the loop. mult = " << mult << "\n";
      }
    std::count << "Loop finished. mult = " << mult << "\n";   
    return 0;
}
prints out this:
Before the loop. mult = 0
In the loop. mult = 0
In the loop. mult = 5
In the loop. mult = 10
In the loop. mult = 15
In the loop. mult = 20
Loop finished. mult = 0

This is because in C++, the variable "mult" inside the loop is a different variable from the variable "mult" outside the loop, and is stored in a different location in memory.
 
  • Like
Likes   Reactions: fog37

Similar threads

  • · Replies 12 ·
Replies
12
Views
2K
  • · Replies 10 ·
Replies
10
Views
4K
  • · Replies 9 ·
Replies
9
Views
5K
  • · Replies 1 ·
Replies
1
Views
3K
  • · Replies 10 ·
Replies
10
Views
2K
  • · Replies 25 ·
Replies
25
Views
6K
  • · Replies 16 ·
Replies
16
Views
3K
  • · Replies 23 ·
Replies
23
Views
3K
  • · Replies 2 ·
Replies
2
Views
2K
  • · Replies 3 ·
Replies
3
Views
2K