The basics of syntax

INPUT · Slides

Changing what kind of value it is

01 / 06

Values come in kinds

So far we have kept "text" and "numbers" apart. That kind is called a type.

These three come up most.

  • str … text ("Aoi", "10")
  • int … whole numbers (10, -3)
  • float … decimals (1.5, 110.0)

02 / 06

type tells you which one it is

Hand a value to type() and it tells you the type. When you are stuck, it lets you check what it is you are actually holding.

It comes out in an odd-looking shape like <class 'int'>. Just read the bit inside the ' as the name of the type.

print(type(10))print(type("10"))print(type(1.5))

Result

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

03 / 06

Looking the same is not being the same

10 and "10" look identical on screen, but to Python they are worlds apart. The difference shows when you add them.

  • 10 + 1020 (adding)
  • "10" + "10"1010 (joining)
print(10 + 10)print("10" + "10")

Result

20
1010

04 / 06

int turns it into a number

To turn text into a number, use int().

Hand it text that is not shaped like a number and you get a ValueError. Only what can be turned gets turned.

text = "10"number = int(text)print(number + 5)

Result

15

05 / 06

str turns it into text

Going the other way, str() turns a number into text. Once it is text, + will join it.

That said, now that f-strings exist you reach for str() less often. Know it so you can read it is about the right level.

price = 150print("$" + str(price))

Result

$150

06 / 06

int throws away the decimal part

int() works on decimals too, where it drops everything after the point. It does not round, so watch out.

float() goes the other way. Once you can move between int, float and str, types will hardly ever trip you up.

print(int(3.7))print(float(3))

Result

3
3.0