Python Lesson 2: Variables, Numbers and Text

📎 This article includes 2 downloadable practice files ↓

⏱ 2 min read

📘 Python Beginner Course · Lesson 2 of 12

In this article
  1. Creating variables
  2. Maths
  3. f-strings: readable output
  4. Text and numbers don’t mix automatically
  5. Useful text methods
  6. Where beginners go wrong
  7. Practice

A variable is a name for a value, like naming a cell in Excel. Instead of remembering that B2 holds the quantity, you write qty = 12 and use qty from then on.

Creating variables

customer = "Sharma Traders"   # text (str)
qty = 12                      # whole number (int)
rate = 60.0                   # decimal (float)
gst_rate = 0.18
paid = False                  # True/False (bool)

Names: lowercase with underscores (gst_rate), no spaces, can’t start with a number. # starts a comment.

Maths

amount = qty * rate              # 720.0
gst = round(amount * gst_rate, 2)
total = amount + gst
Operator Example Result
+ – * / 7 / 2 3.5 (always a decimal)
// 7 // 2 3 (whole-number division)
% 7 % 2 1 (remainder, like MOD)
** 10 ** 2 100 (power)

f-strings: readable output

print(f"{customer}: {qty} x Rs {rate:,.2f} = Rs {amount:,.2f}")
# Sharma Traders: 12 x Rs 60.00 = Rs 720.00

Put an f before the quotes and variables in {}. After a colon come formats: , thousands separator, .2f two decimals, .0% percentage.

💡 Python’s comma format gives 1,234,567 (international grouping). For Indian 12,34,567 grouping, use the babel package or a small helper function; for reports going to Excel, write plain numbers and let Excel format them.

Text and numbers don’t mix automatically

int("42") + 8        # 50
str(42) + "8"        # "428"
"42" + 8             # TypeError!

Data read from files arrives as text, so converting with int() and float() is something you’ll do constantly.

Useful text methods

customer.upper()          # 'SHARMA TRADERS'
customer.lower()
"  ravi kumar ".strip().title()   # 'Ravi Kumar'  (like TRIM + PROPER)
len(customer)             # 14
customer.replace("Traders", "Trading Co")
"INV-2026-0145".split("-")        # ['INV', '2026', '0145']

Where beginners go wrong

Error Cause
NameError: name ‘Qty’ is not defined Python is case-sensitive: qty ≠ Qty
TypeError: can only concatenate str Joining text and a number; use an f-string
0.1 + 0.2 = 0.30000000000000004 Normal floating point; round() money

Practice

Download the script (and data file, if listed) below into one folder. Open a terminal in that folder and run python lesson-NN.py. Compare with the expected output, then change something and run it again: that’s how Python is learned.

📎 Practice files for this article

Free to use for learning. Files with macros (.bas) are plain text — import them with Alt+F11 → File → Import File, and always test on a copy.

✨ Ask AI about this article

Stuck on a step? Ask a question and the AI answers using this article.

Free · AI can be wrong