Codiqo

Learn Python · lesson 4 of 60 · about 7 minutes

Types and Comments

See what type a value really is, why text can't be added to a number, and leave notes in your code.

What you'll learn

  • Tell str, int, float and bool apart with type()
  • Spot text that only looks like a number
  • Write comments with #

Why did 18 + 1 crash?

Your assistant reads your age, 18, from a file, adds 1 for your next birthday, and crashes. To see why, you need to know what type a value is.

Everyday values are one of four types: str (text), int (whole numbers), float (decimals) and bool (True or False). type() tells you which.

type() names the type

print(type("18"))
print(type(18))
print(type(1.5))
print(type(True))

Output

<class 'str'>
<class 'int'>
<class 'float'>
<class 'bool'>

Text that looks like a number

Anything read from a file or typed in by a person arrives as a string, even when it looks like a number. Python won't add a string and a number: it stops with a TypeError instead of guessing.

int() turns text like "18" into the number 18. You'll use it a lot soon.

Turn the text into a number first

age = "18"
print(int(age) + 1)

Output

19

Notes for humans

A comment is a note Python skips. # makes the rest of the line a comment.

Use comments to say *why* the code does something, not what every line does.

Comments are skipped when the code runs

# Run this every morning before work
print("Good morning!")  # the greeting

Output

Good morning!

Tip

True and False start with a capital letter in Python, with no quotes. true is an unknown name, and "True" is just text.

Now try it yourself

This lesson is free in Codiqo, with 9 questions on what you just read. You can only learn to code by writing code, so it ends with a short program you write yourself, which we run and check straight away.