Does the print statement need to be indented?

Does it matter if I indent the print statement? It seems like I get the same thing whether I indent it or not.

My solution was this one


import json
with open("message.json") as message_json:
  pass
  message=json.load(message_json)
print(message['text'])

looks like python needs the variable to be indented under the Pass block in order to save the contento of the json

Print doesn’t need to be indented, as shown here.

However, pass is just a null statement. You use it to test your code when you’re using with before writing anything after it so you don’t get an end of frame error. Once you have the message portion, you can delete pass.

3 Likes

To my suprise, doesn’t seem to matter. The file oject variable seems to be global in nature.

1 Like

If I understand, the end of the “with open…” indented section simply tells Python when to close the file we’re access because we don’t need it any more.

with open('message.json') as message_json:
    message = json.load(message_json)
    print(message)

In this context, if the print function in indented, the text will be printed and then the file will be closed.

with open('message.json') as message_json:
    message = json.load(message_json)

print(message)

If the print function isn’t indented, the file will be closed and then the text will be printed.

They both work, but that’s the difference.

1 Like