Lesson 1 of 3 in this module

4/43 in track

Variables, types & type hints

python8 min

Overview

A pipeline reads text, numbers, and dates from outside systems. Learn how Python names those values, checks their types, and converts text before doing math.

On this page8 sections

What you will do

Open a CSV file in a text editor and you see ORD-1,49.90,3. It looks like an order id, a unit price, and a quantity.

Is 49.90 in a CSV file really a number?

To Python it is just characters. The 49.90 is no more a number than the word banana is.

  1. CSV lineORD-1,49.90,3
  2. Text piecesevery piece is a str
  3. Castfloat() and int()
  1. Typed valuessafe to do math on

This lesson walks that road: hold a value under a name, find its type, and convert text before computing subtotals.

What goes wrong if you skip the conversion?

The price came out of the file as text, the quantity is a whole number, and we multiply. Predict the output: 149.70, or something else?

PythonLooks like a subtotal. Is it?
price_text = "49.90"
qty = 3
print(price_text * qty)
49.9049.9049.90

No error and no total. Text multiplied by 3 repeats the text 3 times without warning.

A silently wrong total is worse than a crash, because it flows into reports unnoticed.

What if you add a number to the text instead?

Adding gives you a loud error, because Python refuses to add a number to text.

PythonNaive code: adding a number directly to text
price_text = "49.90"
tax = 5.0
total = price_text + tax
Traceback (most recent call last):
  File "pipeline.py", line 3, in <module>
    total = price_text + tax
            ~~~~~~~~~~~^~~~~
TypeError: can only concatenate str (not "float") to str

Read the last line first. It names the error type and the two types that clashed.

Words you will see in this lesson

Six words. The rest of the lesson uses only these.

WordWhat it means
VariableA name that points at a stored value
TypeWhat kind of value it is, such as text or number
intA whole number, like 42
floatA number with a decimal point, like 49.90
strText, written inside quotes
CastConvert a value from one type to another

Why this skill

Every external system feeds data into pipelines as text, including CSV files, JSON payloads, and database exports.

What are a variable and a type?

Two ideas cover how Python holds your data.

Four name tags pointing at four values: order_id points at the text ORD-1, qty at the whole number 3, price_text at the text 49.90, price at the decimal 49.9
Names point at values. Each value has its own type.Source: LakeBench · Original diagram

A variable is a name attached to a value. A type is the kind of value it is, and the type decides what operations are allowed.

Notice 49.90 in quotes is text, while 49.9 without quotes is a number. Same digits, different types.

How bad can a wrong type get?

Wrong types can sit quietly until a monthly revenue total comes out completely distorted.

The same price handled three ways.

What you wroteWhat Python didResult
"49.90" * 3Repeated the text49.9049.9049.90
"49.90" + 5.0Refused to mix typesTypeError
float("49.90") * 3Cast first, then multiplied149.7

Only the last row gives a real subtotal. The cast is the whole fix, and it costs one function call.

How the code works

Python works out the type from the value you assign, so you never declare one. The type belongs to the value. The variable is only a name for it.

How do you create a variable and check its type?

Write the name, an equals sign, then the value. You never declare a type. Predict what type() says for True and for None.

PythonFive values, five types
order_id = "ORD-1"
qty = 3
price = 49.9
is_paid = True
note = None

print(type(order_id))
print(type(qty))
print(type(price))
print(type(is_paid))
print(type(note))
<class 'str'>
<class 'int'>
<class 'float'>
<class 'bool'>
<class 'NoneType'>

Python inspects the value and determines the type for you.

The five types you will meet in nearly every lesson.

TypeHoldsExampleTypical use in a pipeline
strText"ORD-1"Ids, names, statuses, anything in quotes
intWhole numbers3Quantities, counts
floatDecimal numbers49.9Prices, measurements
boolTrue or FalseTrueFlags such as is_paid
NoneNo valueNoneA field that was left empty

How do you turn text into a number?

Converting a type is called casting. Each type has a dedicated function: int(), float(), str().

PythonCast first, then multiply
price_text = "49.90"
qty = 3

price = float(price_text)
print(price * qty)
print(type(price), type(qty))
149.7
<class 'float'> <class 'int'>

float("49.90") returns the float 49.9, so multiplying by 3 performs real math. The moment data enters your code, cast it.

Cast at the boundary, trust the type everywhere after.

Can a whole number get too big?

In many languages an integer overflows near two billion. A Python int has no such limit as long as memory lasts.

PythonTwo to the power of 100
print(2**100)
1267650600228229401496703205376

That makes int safe for row counts, transaction IDs, and quantities. Floats are the type that needs care.

Why does 0.1 + 0.2 print a strange number?

Computers store floats in binary, and some decimals cannot be written exactly in binary format.

PythonA famous float surprise
print(0.1 + 0.2)
0.30000000000000004

One subtotal hides the gap. But a pipeline that adds millions of transactions a day can drift into reconciliation mismatches.

Three ways teams keep money exact.

ApproachHowWhen to use it
Round at the endround(x, 2) or f"{x:.2f}"Display and light totals
Integer paise49.90 rupees stored as 4990Transactional systems
Decimal typePython's decimal module, exact base-10Accounting that must match to the penny

What does a variable name really point to?

A name is a tag tied to a value, not a box that holds it. Predict a and b after this runs.

PythonMoving a name tag
a = 100
b = a
a = a + 50
print(a, b)
150 100

Numbers cannot change once created. a + 50 made a new value 150 and moved the tag a to it, while b still points at 100.

How do you join a number to text for a message?

Python will not glue a number onto text. Cast it with str(), or use an f-string.

PythonTwo ways to build a log line
qty = 3
print("Qty: " + str(qty))
print(f"Qty: {qty}")
Qty: 3
Qty: 3

The f-string is shorter and handles the conversion automatically, making it the standard choice in pipeline logs.

Do upper and lower case names differ?

Yes. Price and price are two different names. Standard Python style uses lower case with underscores.

PythonTwo names, two values
Price = 1
price = 2
print(Price, price)
1 2

Mixing cases by accident causes a NameError or reads the wrong value, so stick to snake_case like order_id.

What is a type hint?

Writing qty: int = 3 documents the type you intend. It helps code editors and teammates reading your pull requests.

PythonA hint that is wrong
qty: int = "3"
print(qty)
3

Python ran it without error. Hints are notes for people and editors. Python does not enforce them when the program runs.

Worked examples

Example 1: how do you turn one CSV line into typed values?

One line arrives as text. We split it on commas, then cast each piece into its proper type.

Fields in order: order id, unit price, quantity, is_gift.

Raw line
ORD-1,49.90,3,False
PythonSplit, cast, then compute
line = "ORD-1,49.90,3,False"

order_id, price_text, qty_text, gift_text = line.split(",")

price = float(price_text)
qty = int(qty_text)
is_gift = gift_text == "True"

subtotal = price * qty
print(order_id, subtotal, is_gift)
ORD-1 149.7 False

After the casts. Every value has the type its job needs.

VariableValueType
order_idORD-1str
price49.9float
qty3int
is_giftFalsebool
subtotal149.7float

The is_gift line compares text to the string True. We did not call bool(), and the next check explains why.

Why is bool("False") equal to True?

Python treats any non-empty text as true. Only empty strings, 0, empty collections and None count as false.

PythonTruthiness of text
print(bool("False"))
print(bool(""))
True
False

The string False has five characters, so it is non-empty. For flags from files, compare the text explicitly.

Watch outbool() on text does not check meaning

bool("False") evaluates to True because any non-empty string is considered truthy. Only the empty string "" evaluates to False. When parsing flags from a file, compare the string explicitly: gift_text == "True".

Example 2: what happens when a cast fails?

Casting is strict, and that strictness protects pipelines. Notice what happens when you call int() on decimal text.

PythonNaive cast: int() on decimal text
bad_int = int("49.90")
Traceback (most recent call last):
  File "pipeline.py", line 1, in <module>
    bad_int = int("49.90")
ValueError: invalid literal for int() with base 10: '49.90'

A ValueError alerts you that a field contained unexpected characters, such as the word pending in a price column.

How do you get a whole number from decimal text?

Cast to float first, then to int. Predict the result: 50, or 49?

PythonTwo casts in a row
print(int(float("49.90")))
print(round(49.9))
49
50

int() truncates decimals toward zero without rounding. Use round() when you want mathematical rounding.

What if the price is empty?

Real data feeds regularly contain gaps. The line ORD-9,,3,False has no price.

PythonDefensive conversion
raw = "ORD-9,,3,False"
order_id, price_text, qty_text, gift_text = raw.split(",")

price = float(price_text.strip()) if price_text.strip() else None
print(price)
None

Without the check, float("") crashes with ValueError. None is Python's clean way to represent a missing value.

Why validate at the boundary?

Python never enforces types at runtime. The boundary where data enters, such as a file or API response, is where you cast and validate.

  1. External sourceall text, could be anything
  1. Cast and checksplit, cast, handle empty
  2. Pipeline codetrusts prices are numbers

Inside that boundary, your transformation logic can trust that prices are floats and quantities are ints.

Watch outFloats are approximate, not exact

Decimals like 0.1 cannot be stored with exact precision in binary floats. For single line items the difference is tiny, but summing millions of transactions requires either rounding at the end or using the Decimal module.

How does the whole story replay on ORD-1?

From CSV text to a typed subtotal
  1. The CSV line ORD-1,49.90,3,False arrives as one piece of text.

    1. CSV line
    2. str
  2. split(",") gives four text pieces, each still a str.

    1. str
    2. 4 pieces
  3. float(), int() and a comparison give the right types: 49.9, 3, False.

    1. 4 pieces
    2. float, int, bool
  4. Now 49.9 * 3 is real math: 149.7.

    1. float, int, bool
    2. 149.7
  5. An empty price becomes None instead of crashing the batch.

    1. empty price
    2. None

Four rules to carry forward:

  1. Anything read from a file or API is a string until you convert it.
  2. Cast with int(), float() or an explicit comparison, never bool() on text.
  3. Type hints document intent for editors and checkers, but Python does not enforce them at runtime.
  4. Handle empty and corrupted values at the ingest boundary so inner code can trust types.

Common beginner questions

Why is the number 49.90 printed as 49.9?

Python prints the shortest representation that preserves the numeric value. 49.90 and 49.9 are identical numbers in memory. If you need exactly two decimal places for display, format it: f"{price:.2f}" gives "49.90".

Can a variable change its type later?

Yes. A variable name is only a label, so you can point it at a value of another type. However, doing so in pipeline code makes debugging difficult. Prefer descriptive names, such as price_text for raw input and price for the converted float.

Does capitalization matter in variable names?

Yes. Price and price are two completely separate variables. Standard Python style uses lowercase names with underscores, such as order_id and subtotal_amount.

What comes next

One variable holds one value, but a pipeline processes batches of records. The next lesson covers lists, tuples, dictionaries and sets, the primary containers for collections, and how to select the right structure for each access pattern.

Practice

Run the sample code and observe the printed types. Then complete the exercise: take price text and quantity, cast the price, calculate the subtotal, print it, and assign it to result with a float type hint.

Going further: money is not a float

The lesson showed that 0.1 + 0.2 prints a strange number. For a price that matters, this is not a curiosity: summing many small amounts as floats drifts away from the true total. Predict which of the three totals below is exactly 1.00.

Python10 payments of 0.10
from decimal import Decimal

as_float = 0.0
as_cents = 0
as_decimal = Decimal("0")
for _ in range(10):                  # 10 payments, added one at a time
    as_float += 0.10
    as_cents += 10
    as_decimal += Decimal("0.10")
as_cents = as_cents / 100

print("float  :", as_float, as_float == 1.0)
print("cents  :", as_cents, as_cents == 1.0)
print("decimal:", as_decimal, as_decimal == 1)
float  : 0.9999999999999999 False
cents  : 1.0 True
decimal: 1.00 True

The float total prints 0.9999999999999999 and is not equal to 1.0. Whole cents (integers) and Decimal both give an exact answer.

Floats store binary fractions, and 0.10 has no exact binary form, so each addition carries a tiny error. (The built-in sum() on a list of floats compensates for some of this in recent Python versions, which can hide the problem. A running += total shows it.)

Create a Decimal from a string, not from a float. Decimal(0.1) copies the float's error.

ApproachExact?When to use it
floatNoMeasurements, ratios, anything where a tiny error is fine
Integer cents or paiseYesStoring money in files and databases
decimal.DecimalYesCalculations that need exact decimal places, such as tax

Try a new scenario

A file has price text such as '1,299.50', ' 80 ' and ''. Convert each to integer paise (1,299.50 becomes 129950), and treat the empty one as missing. Predict the three results.

Open the answer

The results are [129950, 8000, None]. Remove the thousands separator, strip spaces, treat an empty string as missing (None) instead of 0, then multiply a Decimal by 100 and convert to int. Doing the multiplication on a Decimal, not a float, avoids a result like 129949.

Why is None better than 0 for the empty price?

Zero is a real price. An empty field means the value is unknown. Treating it as 0 would silently lower an average and hide the data problem.

Close the lesson and explain it

Without scrolling up, explain why summing floats can drift and what you would store instead for a price.

Practicals · load into the editor

After you read the theory, run these in the pane on the right. They execute in this tab, no cluster.

Finished this lesson?

Mark it as read when you could explain it to someone else.

Knowledge Check

Confirm your understanding of the concepts taught in this lesson.

Question 1 of 1

Why is using the 'with' statement (context manager) essential when writing ETL output to files or managing database connections?

Rate:
Was this useful?