pbPassingBI
/
Python basics for data beginner 5 min

Variables and data types

Strings, numbers, booleans, and the type errors that catch people out.

What you'll be able to do
  • Use the core scalar types
  • Convert between them
  • Recognise a type error in real data

The core types

name    = 'Ana'      # str
count   = 42         # int
revenue = 1250.75    # float
active  = True       # bool
missing = None       # NoneType

No type declarations — Python infers from the value. type(x) tells you what something is.

Conversion

int('42')        # 42
float('3.14')    # 3.14
str(42)          # '42'
int(3.9)         # 3, truncates rather than rounds
round(3.9)       # 4

int() truncating rather than rounding causes quiet off-by-one errors in totals.

The classic error

Numbers that are secretly text

A CSV column of numbers frequently arrives as strings. '10' + '5' gives '105', not 15, and sorting puts '100' before '9'.

This is the single most common data-loading problem, and it is why checking df.dtypes immediately after loading is a habit worth forming.

f-strings

name = 'Ana'
total = 1250.756
print(f'{name} spent {total:,.2f}')   # Ana spent 1,250.76

The format spec after the colon handles thousands separators, decimal places and percentages — {x:.1%} renders 0.234 as 23.4%.

Key points
  • Python infers types; check them rather than assuming
  • '10' + '5' concatenates to '105' — numbers arriving as text is the usual cause
  • int() truncates; use round() to round
Check yourself