Python with AI Tutorial · Chapter 5 of 48
Python variables are named containers that hold a value, such as a price, a customer name or a list of invoices. You create a variable simply by assigning to it with =; there is no declaration step and no type keyword. This chapter covers how to name variables, how to assign them, how Python decides their type and how to check it.
Creating a variable
A variable is created the moment you assign a value to a name. Python works out the type from the value, so you never write int or string in front of it the way VBA or Java require. The same name can later hold a different value, even a different type.
customer = "Global Traders Ltd"
invoice_total = 18250.75
items_ordered = 14
is_paid = False
print(customer)
print(invoice_total)
print(items_ordered)
print(is_paid)
Output: Global Traders Ltd 18250.75 14 False
Think of each variable as a labelled cell in a spreadsheet: the label is the name, the contents are the value, and you can overwrite the contents any time. Unlike a spreadsheet cell, though, a Python variable has no fixed position; it exists wherever the program is running.
Naming rules
Python enforces four rules, and the community adds a few conventions on top. Breaking a rule raises SyntaxError; breaking a convention only makes your code harder to read.
| Rule or convention | Allowed | Not allowed |
|---|---|---|
| Must start with a letter or underscore | total, _cache |
2nd_quarter |
| Only letters, digits and underscores | q2_sales |
q2-sales, net price |
| Case-sensitive | rate and Rate are two variables |
– |
| Cannot be a keyword | class_name |
class, if, for |
| Convention: snake_case, lowercase | unit_price |
UnitPrice, unitprice |
| Convention: UPPER_CASE for constants | TAX_RATE = 0.18 |
– |
unit_price = 250
UNIT_LIMIT = 100 # constant by convention
_internal_flag = True # leading underscore signals internal use
q3_revenue = 780000
print(unit_price, UNIT_LIMIT, _internal_flag, q3_revenue)
Output: 250 100 True 780000
list = [1, 2, 3] or sum = 0 works, but it hides the real list() and sum() functions for the rest of the program. Use names such as price_list or running_total instead.Reassigning and updating
Assigning to an existing name replaces its value. Because variables often accumulate totals, Python offers shorthand operators: +=, -=, *= and /=. balance += 500 means exactly balance = balance + 500.
balance = 12000
balance = balance - 4500 # rent paid
balance += 8000 # salary received
balance -= 1200 # utilities
print("Closing balance:", balance)
Output: Closing balance: 14300
Assigning several variables at once
Python lets you assign multiple variables on one line, unpack a list into separate names, or give the same value to several names. These shortcuts are common in real code, especially when a function returns more than one result.
name, department, salary = "Anita Rao", "Marketing", 72000
print(name, "-", department, "-", salary)
q1, q2, q3, q4 = [45000, 52000, 48500, 61000]
print("Second half:", q3 + q4)
opening = closing = 0
print(opening, closing)
Output: Anita Rao - Marketing - 72000 Second half: 109500 0 0
Unpacking requires the counts to match. Three names on the left need exactly three values on the right, otherwise Python raises ValueError: too many values to unpack.
Variables have types, decided by the value
Every value in Python has a type, and the variable takes on the type of whatever it currently holds. The type() function tells you what that is. This is called dynamic typing: the type lives with the value, not with the name.
order_id = 10452
unit_price = 19.99
product = "Wireless mouse"
in_stock = True
sizes = ["S", "M", "L"]
print(type(order_id))
print(type(unit_price))
print(type(product))
print(type(in_stock))
print(type(sizes))
Output: <class 'int'> <class 'float'> <class 'str'> <class 'bool'> <class 'list'>
The next chapter, Python data types, walks through each of these in detail. For now, the key point is that a variable can change type: after order_id = "ORD-10452", type(order_id) becomes str.
Strings need quotes, numbers do not
A very common early bug is mixing up text and numbers. "100" in quotes is a string; 100 without quotes is an integer. They look the same when printed but behave completely differently in arithmetic.
qty_text = "100"
qty_number = 100
print(qty_text + qty_text)
print(qty_number + qty_number)
print(type(qty_text), type(qty_number))
Output: 100100 200 <class 'str'> <class 'int'>
Adding two strings joins them, adding two integers sums them. Data pulled from a CSV file or a web form almost always arrives as strings, which is why the type casting chapter is so important.
Choosing good names
A good variable name tells the reader what the value means without a comment. Prefer monthly_revenue over mr, employee_count over n, and include the unit when it matters: delay_minutes rather than delay. Single letters are fine only for short loop counters or well-known maths (x, i).
headcount = 48
avg_salary_inr = 65000
annual_payroll_inr = headcount * avg_salary_inr * 12
print("Annual payroll (INR):", annual_payroll_inr)
Output: Annual payroll (INR): 37440000
Hand the assistant a script with poor names and ask it to rename everything meaningfully, then explain each choice so you learn the reasoning.
Rename every variable in this Python code following PEP 8 snake_case and making the meaning obvious (this is an invoice calculation). Keep the logic identical, then list each old name, the new name and a one-line reason: a = 2500 b = 0.18 c = a * b d = a + c e = "Sharma Traders" print(e, d)
Test your understanding of dynamic typing by asking for a prediction quiz and checking the answers yourself in VS Code.
Give me a 6-question quiz about Python variables. Each question should show 2-4 lines of Python code that assign and reassign variables (including at least one type change from int to str and one multiple assignment), and ask what type() or print() outputs. Put all the answers at the end so I can check after running the code in Python 3.12.
Common mistakes
- Using a variable before assigning it:
NameError: name 'total' is not defined. Python reads top to bottom. - Typing a hyphen in a name (
net-price). Python reads that asnet minus price. - Starting a name with a digit, such as
2024_sales. Writesales_2024. - Forgetting quotes around text, so
city = Mumbailooks for a variable calledMumbai. - Overwriting built-ins like
str,list,maxorsum.
Exercise
Create variables for an employee: full name (string), hourly rate 45.5, hours worked 160 and a boolean for whether they are full-time. Calculate monthly pay, add a 2000 allowance using +=, and print the name, the pay and the type of the pay variable.
Show answer
full_name = "Rohit Verma"
hourly_rate = 45.5
hours_worked = 160
is_full_time = True
monthly_pay = hourly_rate * hours_worked
monthly_pay += 2000
print(full_name, monthly_pay, type(monthly_pay))
Output: Rohit Verma 9280.0 <class 'float'>
The result is a float because hourly_rate is a float, and multiplying a float by an int always gives a float.
Related chapters
FAQ
Do I need to declare a variable type in Python?
No. Python infers the type from the value you assign, so revenue = 5000 creates an int and revenue = “5000” creates a str. You can add optional type hints later, but they are never required.
What is the difference between a variable and a constant in Python?
Technically none; Python has no true constants. By convention a name in UPPER_CASE such as TAX_RATE tells other programmers not to change it, and linters will warn if you do.
Can a Python variable change its type?
Yes. The type belongs to the value, not the name, so count = 5 followed by count = “five” is legal. It is legal but confusing, so keep one meaning per variable.
Working with spreadsheets too? Ready-made Excel, Google Sheets and Power BI templates are at NextGenTemplates.com.
Chapter 5 of 48 · Python with AI: all 48 chapters



