The basics of syntax

INPUT · Slides

When there is nothing there

01 / 06

A value for "not decided yet"

As you write programs you often want to say "this has not been decided yet".

You could make do with 0 or "" (empty text), but "costs nothing" and "price not decided" are two different things. To say which is which, Python gives you a special value: None.

price = Noneprint(price)

Result

None

02 / 06

None is not any of the others

None is not 0, not False and not empty text. It is a value in its own right, with a type of its own.

It starts with a capital, like True and False. Write none in small letters and you get a NameError.

print(type(None))print(None == 0)

Result

<class 'NoneType'>
False

03 / 06

Check for None with is

To ask whether something is None, the Python habit is to write is None rather than ==.

== None runs perfectly well, but in real Python code you will see is None almost every time. Make sure you can read it.

price = Noneif price is None:    print("not decided yet")

Result

not decided yet

04 / 06

A condition takes any value at all

if will actually take any value, not only the result of a comparison. Python reads it as True or False for you.

The ones treated as False are the empty and the zero things.

  • 0
  • "" (empty text)
  • None
  • False

Everything else counts as True.

number = 0if number:    print("something")else:    print("nothing")

Result

nothing

05 / 06

A short way to say "not empty"

Because of that, instead of if name != "": you can write if name:.

It is short and it reads well, so you will see it constantly in Python. Read it as "if there is something in it".

name = "Aoi"if name:    print(f"hello, {name}")

Result

hello, Aoi

06 / 06

Do not muddle 0 with None

Careful, though. 0 and None are both treated as False.

When you need to tell "no value" apart from "the value is zero", if price: is not enough. You have to spell it out with if price is None:.

This pit gets dug into in real work all the time. Being able to write it short and writing it correctly are two different things.

price = 0if price is None:    print("not decided")else:    print("free")

Result

free