import TheShiraverse
Playground
Module 1 · Topic 1

import TheShiraverse
Variables & Data Types

Variables, int, float, str, bool and None, converting between types, and the three errors every beginner meets. Run every example in your browser.

23 scenes8 practice questions5 interview questionslive runnable code
Today's mission: name a value, know its type, and convert it safely. Press → to move, M for all scenes.
Agenda

What we cover today

01

Variables

  • A name for a value
  • Naming rules
  • Memory, live
02

The 5 basic types

  • int and float
  • str, bool, None
  • The float surprise
03

Converting types

  • type(), int(), float(), str()
  • Errors you will meet
  • Real RetailMart numbers
Main story

The price tag that was text

RetailMart product #1 is the Samsung Animi Max, listed at ₹1,25,812.07. A new analyst reads the price from a file and adds ₹100 handling.

The setup

The price comes out of a file looking perfectly normal: 125812.07. She stores it in a variable called price and moves on.

The bug

Adding 100 crashes with a TypeError. So she adds '100' instead. No error. The answer is 125812.07100: wrong, and silent.

The fix

Files hand Python text. The value was a str, not a number. float() converts it, and now the maths is real maths.

Story → SQL

Same idea you already know from SQL

In SQL every column has a declared type. In Python the type travels with the value, so you have to stay awake.

SQL column typePython typeExample
INT / BIGINTintorder_id = 1
NUMERIC / DOUBLE PRECISIONfloatprice = 125812.07
TEXT / VARCHARstrproduct_name = 'Samsung Animi Max'
BOOLEANboolis_active = True
NULLNonephone = None
Pro tip. Dates have their own type in both worlds. We meet them in Module 2.
Topic 1 · Variables

A variable is a name stuck on a value

Write name = value. Python stores the value and remembers the name. Run it and watch the memory table below the cell.

Pro tip. Change a value and run again. The table always shows what Python remembers right now.
Topic 1 · Variables

Syntax, rules and a few good habits

Assign

One = means store, not "equals". The right side is worked out first.

qty = 2 + 3

Name rules
  • letters, digits, underscore
  • cannot start with a digit
  • no spaces; case matters (Price is not price)
Good habits
  • snake_case names
  • say what it holds: unit_price, not x
  • one idea per variable
Common mistake

Typo or wrong case in a name

Python does not guess. A name that was never created, or spelled with another case, raises NameError.

Broken
Fixed
Watch out. Read the last line of the error first: name 'Price' is not defined tells you exactly what Python could not find.
Topic 2 · Types

Five types cover most of an analyst's day

type() tells you what a value is. Try each one.

int

whole numbers: IDs, counts

order_id = 1

float

decimals: prices, ratios

price = 125812.07

str

text in quotes

city = 'Gwalior'

bool

True or False

is_active = True

None

"no value", like NULL

phone = None

Topic 2 · Types

Which type fits which RetailMart column

ColumnPython typeWhy
orders.order_idintwhole number, never 2.5 orders
orders.net_totalfloatrupees and paise
stores.citystrtext, in quotes
a yes/no flagboolexactly True or False
missing phoneNoneunknown, not zero and not empty text
Pro tip. Test for missing with is None, never == None.
Common mistake

0.1 + 0.2 is not exactly 0.3

Computers store decimals in binary, so some come out a tiny bit off. It even happens with real RetailMart prices.

Broken
Fixed
Watch out. Round for display and comparison. For exact money in finance code, use Decimal; we meet it in the numbers topic.
Topic 3 · Converting

int(), float(), str(), bool() change the type

Data from files and websites arrives as text. Convert it before you do maths.

Watch out. bool('False') is True. Any non-empty text is True. Only 0, empty text, None and empty collections are False.
Common mistake

int() on text that is not a plain number

int() only accepts digits. Decimals and Indian-style commas raise ValueError.

Broken
Fixed
Watch out. Clean first (replace), then convert. For '12.5' go through float() first.
Common mistake

Adding text and a number

Python is strict: it will not mix str and int with +.

Broken
Fixed
Watch out. can only concatenate str (not "int") to str means one side is still text. Convert it.
Real world

Margin on RetailMart product #1

Samsung Animi Max: price ₹1,25,812.07, cost ₹88,068.45. Variables make the formula readable.

Pro tip. This is what a SQL SELECT price - cost AS margin does for every row. In Module 2 pandas does it for all 6,036 products at once.
Practice Arena

Easy and Medium

Type the answer, press Run. Green means correct.

Easy

Store the price 125812.07 in a variable called price and print it.

price = 125812.07 print(price)
Easy

Print the type of the value '125812' (with quotes).

print(type('125812'))
Medium

price arrives as text. Print the total for qty = 3 as a number.

price = '125812' qty = 3 print(int(price) * qty)
Medium

Print the margin (price minus cost) rounded to 2 decimals.

price = 125812.07 cost = 88068.45 print(round(price - cost, 2))
Practice Arena

Hard and Crazy

Predict before you run. These are the traps interviewers like.

Hard

Turn '1,25,812' into a number and add 1000.

text = '1,25,812' print(int(text.replace(',', '')) + 1000)
Hard

Predict first, then print bool(''), bool('False'), bool(0) separated by spaces.

print(bool(''), bool('False'), bool(0))
Crazy

Swap a and b in ONE line (no third variable), then print them.

a = 1 b = 2 a, b = b, a print(a, b)
Crazy

y = x then x changes. Print what y is now.

x = 10 y = x x = 20 print(y)
Interview Studio

Five questions interviewers ask on day one

What is the difference between int and float?
int holds whole numbers, float holds decimals. 5 is an int, 5.0 is a float, and they compare equal (5 == 5.0 is True).
Why is 0.1 + 0.2 not exactly 0.3?
Floats are stored in binary and 0.1 has no exact binary form. The result is 0.30000000000000004. Round for display, or use Decimal for exact money.
Is Python statically or dynamically typed?
Dynamically typed (a name can point to any type) and strongly typed ('1' + 1 is an error, it does not guess).
What is None, and how do you test for it?
None is the single 'no value' object, Python's NULL. Test with x is None.
What does bool('False') return?
True. Any non-empty string is truthy, whatever it says.
Self-Check

Can you answer these without running code?

Click a card to check yourself.

What does type('7') show?
<class 'str'>. Quotes make it text.
What happens with '5' + 5?
TypeError. Convert one side.
int(3.99) gives?
3. It cuts the decimals; it does not round.
Is Price the same as price?
No. Names are case-sensitive.
How do you check a value is missing?
value is None
a, b = b, a does what?
Swaps the two values in one line.
Key Takeaways

Five rules to remember

1 · A variable is a name

name = value stores; the right side is worked out first.

2 · Five types

int, float, str, bool, None. Ask type() when unsure.

3 · Files give text

Convert with int(), float(), str() before maths.

4 · Floats drift

Round for display. Exact money needs Decimal.

5 · None is missing

Test with is None. Not zero, not empty text.

6 · Read the last error line

NameError, TypeError, ValueError each say what is wrong.

Quick Reference

Every syntax from today

Assign

Check a type

Convert

Round

Missing value

Swap

Take-Home Challenge

Product #2 of RetailMart

Samsung Recusandae Lite: price ₹1,06,495.49, cost ₹74,546.84. Work in the cell below, then check against a classmate or in a 1:1.

  1. Store price, cost and the product name in variables.
  2. Print the margin in rupees, rounded to 2 decimals.
  3. Print the margin percent, rounded to 2 decimals.
  4. The price arrives as '1,06,495.49'. Convert it to a float.
  5. Print type() of every variable you made.
Your Python journey

Module 1: Python Foundations

You are here: topic 1 of 14.

1. Variables & types2. Numbers & operators3. Strings & f-strings4. Input, output & errors5. Lists6. Tuples & sets7. Dictionaries8. Conditions9. Loops10. Functions11. Comprehensions12. Files, CSV & JSON13. Modules & imports14. Error handling
Next topic

Numbers & Operators

Arithmetic, integer division, modulo, powers, rounding, and exact money with Decimal. You will use every one of them on RetailMart orders.

Before the next topic: finish the take-home and play with the playground: python.theshiraverse.com/playground