The 1st block gets an indentation but not the 2nd?

I am a total beginner and I thought I understood indentation.

I do not understand as to why the 1st block gets indentation but the 2nd does not?

x = “uh huh”

def myfunc():
x = “sure”
print("life is " +x)

myfunc()
print("Life is " +x) # I am looking at this print function and myfunc() directly above it. Why no indentation?
When I ‘run’ print with an indent I get an indent error…

The 1st block is indented:

x = “uh huh”

def myfunc():
x = “sure”
print("life is " +x)

We can’t see your indentation so this is hard to explain.

If you format your code in a code block, surrounded by three backticks (```), the indentation will be preserved.

x = “uh huh”

def myfunc():
    x = “sure”
print("life is " +x)

I just noticed this site did not show my indent. Here it is again

x = “uh huh”

def myfunc():
'x = “sure” (single-indent)
'print("life is " +x) (single-indent)

myfunc()
print("Life is " +x) *** NO INDENT HERE ?!***

The 1st block is indented:

x = “uh huh”

def myfunc():
'x = “sure” (single-indent)
'print("life is " +x) (single-indent)

please use the actual code formatting, it is very easy to do. Three backticks around the block (the key with the ~ on it, on a US keyboard). You can check the preview of your post to make sure it works.

x = “uh huh”

def myfunc():

```print("life is " +x)


myfunc()
print("Life is " +x)       (THIS BLOCK DOESN'T GET AN INDENT?) 



The 1st block is indented:

x = “uh huh”

def myfunc():
```x = “sure”
```print("life is " +x)

Well…an effort was made, at least :slightly_smiling_face:

Indentation is used to denote a block of code, as in the code following the function definition def myfunc(): (note the colon at the end of the line, telling us that what follows will be a new block of code)

There’s no indentation after the call to myfunc because calling a function doesn’t denote the beginning of a new block of code.

Other situations where you would indent a block are conditional statements:

if something_is_true:
    do_this_when_true()
else:
    do_something_else()

Or in for loops (for i in range(10): ...) or many other cases. In general, when you see a : at the end of a line, that’s a sign that a new block is starting.

1 Like

Ah! The colon explanation makes sense to me me now. As well as your example.

Thank you very much for taking the time to help me with this issue. (Big thumbs up) I was frustrated.

I need to get my head around the syntax.

I should just add that the colon character is used in other places too (like dictionaries). That explanation is a useful rule of thumb for getting started, but as you get more familiar with Python I wouldn’t want you think I lied to you. :sweat_smile:

1 Like

Please read the pinned thread to understand how to do the code formatting properly, and see if you can edit the previous posts to fix them.