The basics of syntax

INPUT · Slides

Writing comments

01 / 06

From # to the end of the line is a note

Write a # (a hash) and Python ignores everything from there to the end of the line.

You have actually been seeing them since the first lesson. That # write your code here line in the starter code was one.

# just a note. this does not runprint("this one runs")

Result

this one runs

02 / 06

You can put one after code too

Start the # partway along a line and only the rest of that line becomes a note. The code in front of it still runs.

By convention you leave two spaces between the code and the #, to keep it readable.

print(1000 - 430)  # working out the change

Result

570

03 / 06

Switching a line off for a while

# is good for more than notes. Put one at the start of a line you do not want to run, and it disappears for now.

That is called "commenting a line out". Delete a line and getting it back is a pain; comment it out and you just take the # off again. When you are hunting for what broke, this earns its keep.

print("one")# print("two")print("three")

Result

one
three

04 / 06

What to put in one

What belongs in a comment is not the thing the code already says.

  • print(x) # show x … you can see that
  • print(x) # here for now, to check it is working … you cannot see that

Write why. The code is already telling everyone what.

05 / 06

A comment is a letter to your future self

Treat the you of three days from now as a stranger. "Why on earth did I write it like this?" is going to happen.

What saves you then is the one line that felt too obvious to bother writing down.

Do not go too far the other way, though. Code covered in comments is often a sign the code itself is unclear. Write readable code first, then patch the gaps with comments.

06 / 06

Write in whatever language you think in

A comment can be in any language you like. It never runs, so Python is not reading it.

The right answer is whatever you can read fastest. Forcing it into a language you are less sure of, and losing the meaning, would be a waste.

# work out the price with the tax addedprint(100 * 1.1)

Result

110.00000000000001