Skip to content
TeachTrails
Data EngineeringPython

Python Basics: Variables, Types and Strings

Python's building blocks for data work: numbers, text, booleans, None, f-strings, string cleaning, type conversion and why money needs Decimal, with real output.

Sukanya Saha, Technology Consultant

10 min read

Beginner friendly

Variables and types

Python
order_id = 101              # int: whole number
price = 1999.0              # float: decimal number
product = "Headphones"      # str: text
delivered = True            # bool: True / False
coupon = None               # None: "no value"

print(type(order_id), type(price), type(product), type(delivered), type(coupon))
Output
<class 'int'> <class 'float'> <class 'str'> <class 'bool'> <class 'NoneType'>
TypeExampleLike in SQL
int101, -5, 1_000_000INT / BIGINT
float1999.0, 0.18DOUBLE (approximate)
str'Headphones', "Kolkata"TEXT / VARCHAR
boolTrue, FalseBOOLEAN
NoneNoneNULL

Names use snake_case by convention: order_id, not OrderId.

Numbers and arithmetic

Python
quantity = 3
unit_price = 499
print(quantity * unit_price)     # 1497
print(7 / 2)                     # 3.5  (/ always gives a float)
print(7 // 2)                    # 3    (whole-number division)
print(7 % 2)                     # 1    (remainder)
print(2 ** 10)                   # 1024 (power)
print(round(1999 * 1.18, 2))     # price with 18% GST
Output
1497
3.5
3
1
1024
2358.82

Strings: the data cleaner's toolbox

Python
raw = "  Headphones  "
print(repr(raw.strip()))                      # remove spaces at both ends
print("delivered".upper())                    # DELIVERED
print("Phone Case".lower().replace(" ", "_")) # phone_case
print("101,1,Headphones".split(","))          # text → list
print(" | ".join(["Asha", "Kolkata"]))         # list → text
print("Smart" in "Smartwatch", "2026-04-01".startswith("2026"))
Output
'Headphones'
DELIVERED
phone_case
['101', '1', 'Headphones']
Asha | Kolkata
True True
MethodDoesExample result
.strip()Remove spaces/newlines at both ends'Headphones'
.upper() / .lower() / .title()Change case'DELIVERED'
.replace(a, b)Replace text'phone_case'
.split(',')Text → list['101', '1', ...]
', '.join(list)List → text'Asha, Kolkata'
.startswith() / inChecksTrue
.isdigit()Only digits?'12'.isdigit() → True

f-strings: formatting output

Python
name, amount, pct = "Asha", 8092.5, 0.2345
print(f"{name} spent ₹{amount:,.2f}")    # thousands separator, 2 decimals
print(f"Share of revenue: {pct:.1%}")    # as a percentage
print(f"{'Order':<8}|{'Amount':>10}")     # left / right align in a column
print(f"{101:<8}|{1999:>10,}")
Output
Asha spent ₹8,092.50
Share of revenue: 23.4%
Order   |    Amount
101     |     1,999

After the colon: , thousands separator, .2f two decimals, .1% percentage, <8/>10 align in a column of that width.

Converting between types

Everything read from a CSV or an API arrives as text, so conversion is constant work:

Python
print(int("3") + 1)          # text → int
print(float("1999"))          # text → float
print(str(101) + "-A")       # int → text
print(bool(""), bool("x"), bool(0), bool([]))   # empty things are False
Output
4
1999.0
101-A
False True False False
Python
quantity = int("two")
Output
ValueError: invalid literal for int() with base 10: 'two'

One bad value stops the program. Lesson 6 shows how to catch this and keep the row for review instead of crashing.

None: Python's NULL

Python
city = None
if city is None:             # use "is None", not "== None"
    city = "Unknown"
print(city)
Output
Unknown

Float surprises and money

Python
from decimal import Decimal

print(0.1 + 0.2)                            # floats are binary approximations
print(Decimal("0.1") + Decimal("0.2"))      # exact: use Decimal for money
Output
0.30000000000000004
0.3

Putting it together: parse one CSV line

Python
line = "105,4, Headphones ,1,1999,DELIVERED,2026-04-07"

order_id, customer_id, product, quantity, price, status, order_date = line.split(",")
product = product.strip()
amount = int(quantity) * float(price)

print(f"Order {order_id}: {product} × {quantity} = ₹{amount:,.0f} ({status.title()})")
Output
Order 105: Headphones × 1 = ₹1,999 (Delivered)

Unpacking (a, b, c = parts) names each piece, strip removes the stray spaces around “Headphones”, and conversion makes maths possible. Lesson 5 does this properly with the csv module.

🎯 Interview questions on this topic

Try to answer out loud first, then tap to check.

Q1What are Python's basic data types?Fresher
int, float, complex, str, bool and NoneType, plus collections (list, tuple, dict, set) covered in the next lesson.
Q2Mutable vs immutable types?Fresher
Immutable values can't change after creation: int, float, str, bool, tuple, frozenset. Mutable ones can: list, dict, set. 'Changing' a string actually creates a new string.
Q3Why use 'is None' instead of '== None'?1–3 yrs
None is a single object, so identity (is) is exact and fast; == can be overridden by a class's __eq__ and give surprising results.
Q4How do you handle floating-point precision in financial data?1–3 yrs
Use decimal.Decimal constructed from strings, or integers in the smallest unit (paise). Round only at presentation, and use NUMERIC/DECIMAL columns in databases.
Q5What does dynamic typing mean?1–3 yrs
Variables don't have fixed types; values do, and types are checked at run time. Type hints (price: float) document intent and let tools like mypy catch mistakes before running.

Key takeaways

  • Know the five basic types and convert between them carefully.
  • String methods are the core of everyday data cleaning.
  • f-strings make readable output; Decimal keeps money exact.
  • Next: lists, dicts and sets for working with many records.

Frequently asked questions

What is a variable in Python?

A name that points to a value: price = 1999. You don't declare a type; Python works it out from the value, and the same name can later point to something else.

What is the difference between / and //?

/ always returns a float (7 / 2 = 3.5). // is floor division and returns the whole-number part (7 // 2 = 3). % gives the remainder.

Why is 0.1 + 0.2 not 0.3?

Floats are stored in binary, which can't represent 0.1 exactly, so tiny errors appear. For money use decimal.Decimal or store whole paise/cents as integers.

What is None?

Python's 'no value', like NULL in SQL. Check it with 'is None', not '== None'.

What is an f-string?

A string starting with f that fills in {expressions}: f"Total: {total:,.2f}". It's the modern, readable way to format text in Python 3.6+.

🧠 Quick check: Python basics

  1. 1. type(1999.0) is...

  2. 2. " Charger ".strip() returns...

  3. 3. int("two") ...

  4. 4. Best type for money?

Python for Data Engineers

Part 2 of 13: Python Basics