All 57 lessons
Lesson 3 of 57 · Getting Started
Variables and Data Types in Python
By Skillancy Editorial Team
Run the code in the free Python Compiler or on your own computer. Lessons that read files use the FreshBasket practice data: download the dataset (ZIP).
Every analysis starts with values: the number of orders, a customer's name, whether a delivery was late, the date an order was placed. A variable is a name you attach to a value so you can use it again later. A data type tells Python what kind of value it is, which decides what you are allowed to do with it. You cannot divide a name by a city, and Python knows that because of types.
This lesson is the foundation for everything that follows. Take your time with it, run the examples yourself and change the numbers. Almost every error message you will see in your first month traces back to a mix-up between variables or types.
What is a variable?
Think of a variable as a label stuck on a box. The box holds a value, and the label is the name you use to find it. When you write:
orders_today = 412Python does three things in order: it creates the value 412 in memory, creates the name orders_today, and connects the name to the value. The = sign here is assignment, not "equals" as in maths. Read it as "let orders_today refer to 412".
Because a name is just a label, you can move it. After orders_today = 450, the label now sits on a new box and the old value is forgotten. This is why variables are called variable: what they point to can change.
The five basic data types
| Type | Name | Example | Used for |
|---|---|---|---|
int | Integer | 412, -7, 0 | Counts: orders, items, days |
float | Floating-point number | 486.5, 0.05 | Measurements and money: prices, averages, rates |
str | String | "Bengaluru" | Text: names, cities, emails |
bool | Boolean | True, False | Yes/no flags: is_prime, is_late |
NoneType | None | None | "No value": a missing delivery time |
There are more types (lists, dictionaries, dates), and they each get their own lesson. These five are the atoms that everything else is built from.
Naming variables
Python is strict about a few rules and relaxed about the rest, but professional analysts follow conventions that make code readable months later.
Rules (Python enforces these):
- Names may contain letters, digits and underscores.
- A name cannot start with a digit.
- A name cannot contain spaces or symbols like
-,$or₹. - A name cannot be a reserved word such as
class,iforfor. - Names are case-sensitive:
Revenueandrevenueare different.
Conventions (people follow these):
- Use
snake_case: lowercase words joined by underscores, e.g.avg_delivery_minutes. - Choose descriptive names:
delivery_minutesbeatsdm, andxtells nobody anything. - Write constants in
UPPER_CASE, for exampleFREE_DELIVERY_THRESHOLD = 299. Python does not stop you from changing it; the capitals are a signal to humans.
Worked examples
Example 1: Creating variables for one order
Question: Store the details of a single FreshBasket order in variables and print them.
order_id = "O02299"
customer_city = "Bengaluru"
items_count = 4
basket_value = 612.75
is_prime_member = True
coupon_code = None
print(order_id, customer_city, items_count, basket_value, is_prime_member, coupon_code)Output
O02299 Bengaluru 4 612.75 True NoneHow it works: Each line creates a variable. The order id and city are text, so they sit inside quotes. The item count is a whole number, the basket value has decimals, the prime flag is True, and coupon_code is None because this order did not use a coupon. print accepts several values separated by commas and shows them with a space between each.
Reading the result: The six values appear in one line. None prints as the word None, which is Python's way of saying "nothing here".
Example 2: Asking Python for the type
Question: How can I check what type a variable is?
print(type(order_id))
print(type(items_count))
print(type(basket_value))
print(type(is_prime_member))
print(type(coupon_code))Output
<class 'str'>
<class 'int'>
<class 'float'>
<class 'bool'>
<class 'NoneType'>How it works: type() returns the type of whatever you give it. Python writes the answer as <class 'int'>, where "class" is the more general word for type.
Reading the result: order_id is a str, items_count an int, basket_value a float, is_prime_member a bool, and coupon_code a NoneType. Checking types is the first thing to do when a calculation behaves strangely.
Example 3: Types decide what operations work
Question: What happens if I add a number to text?
print(order_id + items_count)Output
Traceback (most recent call last):
File "example.py", line 1, in <module>
print(order_id + items_count)
~~~~~~~~~^~~~~~~~~~~~~
TypeError: can only concatenate str (not "int") to strHow it works: The + operator means "add" for numbers and "join" for strings, but it cannot mix the two. Python refuses rather than guessing, and the error message tells you exactly which types clashed.
Reading the result: The TypeError says it can only concatenate (join) str to str, so it will not combine text with an integer. The fix is to convert one side: order_id + str(items_count) gives text, or you can use an f-string. We cover conversion in lesson 6.
Example 4: Reassigning and updating
Question: A customer adds two more items to the cart. Update the count, then add a delivery fee to the basket value.
items_count = items_count + 2
basket_value = basket_value + 25
print(items_count, basket_value)Output
6 637.75How it works: items_count = items_count + 2 first evaluates the right side (4 + 2 = 6), then points the name at the result. The same happens for the basket value, which grows by the ₹25 fee.
Reading the result: The cart now has 6 items worth ₹637.75. Python also offers shorthand operators, +=, -=, *= and /=, that do the same thing in fewer keystrokes: items_count += 1 means items_count = items_count + 1. Let us use them for one more update, a 5% GST-style uplift on the basket:
items_count += 1
basket_value *= 1.05
print(items_count, round(basket_value, 2))Output
7 669.64After the shorthand updates we have 7 items and ₹669.64. The shorthand is used constantly for counters and running totals.
Example 5: Multiple assignment and swapping
Question: Set several variables at once, and swap two values.
store_a = store_b = 0
morning_orders, evening_orders = 120, 185
print(store_a, store_b, morning_orders, evening_orders)
morning_orders, evening_orders = evening_orders, morning_orders
print(morning_orders, evening_orders)Output
0 0 120 185
185 120How it works: store_a = store_b = 0 points both names at the same value. The comma form a, b = 120, 185 unpacks two values into two names in one statement. The swap works because Python evaluates the whole right side first (the pair 185, 120) and only then assigns, so no temporary variable is needed.
Reading the result: The names swapped values cleanly: morning is now 185 and evening is 120. This idiom is a Python favourite.
Example 6: Invalid names
Question: What happens if I break the naming rules?
2nd_order = "O00002"Output
File "example.py", line 1
2nd_order = "O00002"
^
SyntaxError: invalid decimal literalclass = "Premium"Output
File "example.py", line 1
class = "Premium"
^
SyntaxError: invalid syntaxHow it works: Names cannot start with a digit, and class is a reserved word that Python needs for itself. Both produce a SyntaxError before any code runs, which means the problem is with the grammar of the line itself.
Reading the result: A SyntaxError points at the offending part of the line with carets. Rename the variable (order_2 and customer_class) and the problem disappears. Also avoid reusing built-in names such as list, sum, max or type for variables, because doing so hides the built-in function and causes confusing errors later.
Example 7: None means "no value"
Question: One order was cancelled so it has no delivery time. How do I represent that, and how do I test for it?
delivery_minutes = None
print(delivery_minutes is None)
print(delivery_minutes == 0)
delivery_minutes = 27
print(delivery_minutes is None)Output
True
False
FalseHow it works: None is a special value that means "nothing". Use is None to test for it. Note that None is not the same as 0: zero minutes is a real (impossible) delivery time, whereas None says the information does not exist.
Reading the result: The first test prints True, the comparison with zero prints False, and after we assign 27 the is None test becomes False. In pandas the equivalent of None is a missing value (NaN), which you will meet in the data cleaning lessons.
Example 8: Dynamic typing
Question: Can a variable change type during a program?
x = 10
print(type(x))
x = "ten"
print(type(x))
x = 10.0
print(type(x), isinstance(x, float), isinstance(x, int))Output
<class 'int'>
<class 'str'>
<class 'float'> True FalseHow it works: Python is dynamically typed: the type belongs to the value, not to the variable name. The same label x can point at an integer, then text, then a float. isinstance(value, type) is the cleaner way to ask "is this a float?" and returns True or False.
Reading the result: The three prints show int, then str, then float. This flexibility makes Python quick to write, but it also means mistakes surface at run time rather than before. Good naming and a habit of checking type() when results look odd protect you.
Common mistakes
1. Confusing = with ==. A single = assigns; a double == compares. Writing if x = 5: is a syntax error.
2. Using a variable before creating it.
print(total_discount)Output
Traceback (most recent call last):
File "example.py", line 1, in <module>
print(total_discount)
^^^^^^^^^^^^^^
NameError: name 'total_discount' is not defined3. Overwriting a built-in name. If you write max = 50, you can no longer call max([1, 2, 3]). Pick names like max_orders instead.
4. Believing that b = a copies the value for lists and other mutable objects. For numbers and strings the difference does not show, but you will see in the lists lesson that two names can point at the same list. Keep this idea in the back of your mind.
5. Quotes around numbers. "412" is text, not a number. "412" + "8" gives "4128", not 420.
Practice questions
Practice 1 (Easy): Describe a product
Create variables for a product: product_name ("Masala Chai 500g"), price (245), in_stock (True). Print them in one line.
Show solution
product_name = "Masala Chai 500g"
price = 245
in_stock = True
print(product_name, price, in_stock)Output
Masala Chai 500g 245 TrueEach variable holds a different type: str, int and bool. print shows them separated by spaces.
Practice 2 (Medium): Update a running total
Start with revenue = 0. Add three orders of ₹480, ₹1250.50 and ₹615 using +=, then print the total and its type.
Show solution
revenue = 0
revenue += 480
revenue += 1250.50
revenue += 615
print(revenue, type(revenue))Output
2345.5 <class 'float'>The total starts as an int, but adding a float turns it into a float: Python upgrades the type automatically so no decimals are lost. The final value is 2345.5.
Practice 3 (Hard): Swap and check
Two stores have these delivery averages: store_x = 22.5 and store_y = 27.0. Swap them without a third variable, then print which one is now the smaller and what the type of each is.
Show solution
store_x, store_y = 22.5, 27.0
store_x, store_y = store_y, store_x
print("x:", store_x, "y:", store_y)
print("smaller:", min(store_x, store_y))
print(type(store_x), type(store_y))Output
x: 27.0 y: 22.5
smaller: 22.5
<class 'float'> <class 'float'>Tuple-style assignment swaps in one statement. min() returns the smaller of its arguments, and both values remain floats throughout.
Key takeaways
- A variable is a name attached to a value, created with
=; reassigning moves the name to a new value. - The five basic types are
int,float,str,boolandNone. Check any value withtype()orisinstance(). - Use descriptive
snake_casenames, never start with a digit, and do not reuse reserved words or built-in names. - Types decide which operations are legal; mixing text and numbers raises a
TypeError. +=,-=,*=and/=update a variable compactly, anda, b = b, aswaps two values.Nonemeans "no value" and is tested withis None; it is not the same as zero or an empty string.
Frequently asked questions
Do I have to declare a variable's type in Python?
No. Python works out the type from the value you assign. In languages such as Java or C you must declare types up front, which is one reason Python is quicker to learn.
What is the difference between int and float?
An int is a whole number with no decimal point, and a float can hold fractions. Counts such as orders are usually integers; prices, averages and percentages are floats. Mixing them in arithmetic gives a float.
Can a variable name use Hindi or other non-English letters?
Python 3 allows many Unicode letters in names, so it is technically possible. For code that colleagues and tools need to read, stick to plain English letters, digits and underscores.
Why does type(True) give bool and can I do maths with it?
Booleans are a subtype of integers: True behaves like 1 and False like 0. For example True + True is 2. Analysts use this to count how many items satisfy a condition by summing booleans.
What happens to the old value when I reassign a variable?
If no other name refers to it, Python automatically frees the memory (garbage collection). You do not have to do anything.
Are there constants in Python?
Not enforced ones. By convention you write the name in capitals (MAX_ORDERS = 500) and agree not to change it. Tools such as linters can warn you if you do.
Keep learning Python
One email a week with Python and analytics guides, new practice questions and cohort dates. No spam, unsubscribe anytime.
Ready to practise? Try the Python interview questions