Nested structures and indentation in Python

In summary, indentation is important and mandatory in Python to separate code into blocks. Blocks with the same indentation are considered part of the same block, and indentation is necessary for nested loops and if-statements. Removing indentation can result in syntax errors. In the provided code sample, the if statement after the for loop is considered nested due to its indentation. The next line of code is necessary to print a message when the letter is found.
  • #1
fog37
1,568
108
TL;DR Summary
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
  • #2
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 fog37
  • #3
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 fog37
  • #4
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!")

*****************************************************
 
  • #5
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 fog37
  • #6
Search for letter in the text:
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!")

Thank you.
 
  • #7
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 fog37
  • #8
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 jack action
  • #9
Also, without the indentation, you will get a compilation error.
 
  • Like
Likes 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 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 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:
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
 
  • #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:
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
Yes, you can do that. In such a case, you don't even need the variable found at all.
 
  • Like
Likes 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::cout << "Before the loop. mult = " << mult << "\n";
    for (int i = 0; i < 5; i++)
      {
    int mult = i * 5;
    std::cout << "In the loop. mult = " << mult << "\n";
      }
    std::cout << "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 fog37

1. What is the purpose of nested structures in Python?

Nested structures in Python allow for the creation of data structures within data structures. This allows for more complex and organized data storage and manipulation.

2. How do you create a nested structure in Python?

To create a nested structure in Python, you can use lists, dictionaries, or tuples within lists, dictionaries, or tuples. For example, a list within a list would look like [[1,2], [3,4]].

3. What is indentation in Python?

In Python, indentation is used to indicate a block of code. It is important for maintaining the structure and readability of the code. Indentation is typically done using four spaces.

4. Why is indentation important in Python?

Indentation is important in Python because it is used to indicate a block of code, such as a loop or a conditional statement. Without proper indentation, the code will not run correctly and may result in errors.

5. Can you have multiple levels of indentation in Python?

Yes, you can have multiple levels of indentation in Python. This is necessary when creating nested structures or when using conditional statements within loops. It is important to maintain consistent indentation throughout the code to ensure it runs correctly.

Similar threads

  • Programming and Computer Science
Replies
10
Views
2K
  • Programming and Computer Science
Replies
7
Views
466
  • Programming and Computer Science
Replies
1
Views
275
  • Programming and Computer Science
Replies
10
Views
1K
  • Programming and Computer Science
Replies
25
Views
3K
  • Programming and Computer Science
Replies
16
Views
1K
  • Programming and Computer Science
Replies
23
Views
2K
  • Programming and Computer Science
Replies
2
Views
2K
  • Programming and Computer Science
Replies
9
Views
3K
Back
Top