Variables, Data Types & Expressions
2982 words
15 min read
Visual companion
Python
Type and operator map
Python Week 1: the first filter for runtime behavior
View
Revision summary
What this note is really saying
Short form
# Variables, Data Types & Expressions > **Why read this?** In the last topic, you printed values directly. But real programs need to _remember_ data — a user's name, a score, a calculation result.

Variables, Data Types & Expressions
Why read this? In the last topic, you printed values directly. But real programs need to remember data — a user's name, a score, a calculation result. Variables are your program's "sticky notes" — named boxes where you store information for later use.
🎯 Learning Objectives
By the end of this topic, you will be able to:
- Create variables and assign values to them
- Follow Python's rules for naming variables
- Understand dynamic typing — how a variable's type can change
- Write arithmetic expressions using operators
- Use assignment operators (
+=,-=, etc.) as shortcuts - Convert between data types using
int(),float(),str()
📋 Prerequisites
- Introduction to Programming & Python — You need to understand
print(), data types, and the REPL. - Basic arithmetic: addition, subtraction, multiplication, division.
📖 Core Content
2.1 What Problem Do Variables Solve?
Intuition: Imagine you're calculating the total cost of items in a shopping cart. You'd need to remember the price of each item as you add them up. Without variables, you'd have to type every number again and again. Variables let you give a name to a value and refer to it later.
python# Without variables — repetitive and hard to change print(10 + 5 + 3) print("Total is", 10 + 5 + 3) # typed the numbers again! # With variables — clean and modifiable price1 = 10 price2 = 5 price3 = 3 total = price1 + price2 + price3 print("Total is", total)
2.2 Variables as Labels
Mental model: Think of a variable as a labeled box in your computer's memory.
Diagram
Rendering diagram
- The variable name is the label on the box.
- The value is what's stored inside the box.
- The assignment statement (
=) is the act of putting something in the box.
2.3 Variable Assignment
The
= sign in Python is the assignment operator — it takes the value on the right and stores it in the variable named on the left.python# runnable name = "Alice" # string variable age = 25 # integer variable height = 5.6 # float variable is_student = True # boolean variable print(name) print(age) print(height) print(is_student)
Output:
pseudoAlice 25 5.6 True
Line-by-line:
name = "Alice"— Python creates a box labelednameand puts the string"Alice"in it.age = 25— Creates a box labeledagewith the integer25.- When we
print(name), Python looks in the box labeledname, finds"Alice", and displays it.
2.4 Variable Naming Rules
Python has strict rules for valid variable names:
| Rule | Examples | Why? |
|---|---|---|
| Start with a letter or underscore | name ✅ _count ✅ 1st ❌ | Python uses the first character to decide if it's a variable name or a number |
| Remaining: letters, digits, underscore | my_var2 ✅ my-var ❌ my var ❌ | Only alphanumeric and underscore are allowed |
| Case-sensitive | Age, age, AGE are three different variables | Python distinguishes uppercase and lowercase |
| Can't be a Python keyword | if ❌ for ❌ while ❌ | Keywords are reserved for Python's syntax |
Python keywords you cannot use as variable names:
sqland, as, assert, break, class, continue, def, del, elif, else, except, False, finally, for, from, global, if, import, in, is, lambda, None, nonlocal, not, or, pass, raise, return, True, try, while, with, yield
2.5 Dynamic Typing — Python's Special Feature
What problem does this solve? In some languages (like C++ or Java), you must declare a variable's type upfront and it can never change. Python is more flexible — a variable can hold any type of data, and the type can change during the program.
python# runnable thing = "Hello" # thing is a string print(type(thing)) # <class 'str'> thing = 42 # Now thing is an integer print(type(thing)) # <class 'int'> thing = 3.14 # Now thing is a float print(type(thing)) # <class 'float'> thing = True # Now thing is a boolean print(type(thing)) # <class 'bool'>
Output:
java<class 'str'> <class 'int'> <class 'float'> <class 'bool'>
⚠️ Warning: Just because you can change a variable's type doesn't mean you should. It's usually best to keep a variable's type consistent throughout your program. Changing types unexpectedly is confusing and leads to bugs.
2.6 Multiple Assignment
Python lets you assign values to multiple variables in one line:
python# runnable # Assign multiple variables at once x, y, z = 10, 20, 30 print(x, y, z) # Assign the same value to multiple variables a = b = c = 0 print(a, b, c) # Swap two variables (neat Python trick!) m = 5 n = 10 m, n = n, m # swap! print("m =", m, "n =", n)
Output:
pseudo10 20 30 0 0 0 m = 10 n = 5
2.7 Arithmetic Operators
Python supports all the standard arithmetic operations:
| Operator | Operation | Example | Result | Explanation |
|---|---|---|---|---|
+ | Addition | 10 + 3 | 13 | Adds two numbers |
- | Subtraction | 10 - 3 | 7 | Subtracts right from left |
* | Multiplication | 10 * 3 | 30 | Multiplies two numbers |
/ | Division | 10 / 3 | 3.333... | Always returns a float |
// | Floor division | 10 // 3 | 3 | Divides and rounds DOWN to nearest integer |
% | Modulus (remainder) | 10 % 3 | 1 | Returns remainder of division |
** | Exponentiation | 10 ** 3 | 1000 | Left to the power of right |
2.8 Worked Example 1: Basic Arithmetic
python# runnable a = 15 b = 4 print("a + b =", a + b) # 19 print("a - b =", a - b) # 11 print("a * b =", a * b) # 60 print("a / b =", a / b) # 3.75 (float division) print("a // b =", a // b) # 3 (floor division: 15/4 = 3.75, rounded DOWN to 3) print("a % b =", a % b) # 3 (remainder: 15 = 4*3 + 3) print("a ** b =", a ** b) # 50625 (15*15*15*15)
Output:
pseudoa + b = 19 a - b = 11 a * b = 60 a / b = 3.75 a // b = 3 a % b = 3 a ** b = 50625
2.9 Operator Precedence (Order of Operations)
Python follows the standard mathematical order of operations (PEMDAS/BODMAS):
Parentheses → Exponents → Multiplication/Division → Addition/Subtraction
python# runnable print(2 + 3 * 4) # 14 (3*4=12, then 2+12=14) print((2 + 3) * 4) # 20 (2+3=5, then 5*4=20) print(10 - 2 ** 3) # 2 (2**3=8, then 10-8=2) print(10 / 2 * 3) # 15.0 (left to right: 10/2=5, then 5*3=15) print(10 * 2 ** 3) # 80 (2**3=8, then 10*8=80)
Output:
pseudo14 20 2 15.0 80
Pro tip: When in doubt, use parentheses()to make your intention clear. It's better to write(2 + 3) * 4than to rely on remembering precedence rules.
2.10 Assignment Operators (Shortcuts)
These operators let you modify a variable and assign the result back in one step:
python# runnable x = 10 x += 5 # same as: x = x + 5 print("After x += 5:", x) # 15 x -= 3 # same as: x = x - 3 print("After x -= 3:", x) # 12 x *= 2 # same as: x = x * 2 print("After x *= 2:", x) # 24 x //= 5 # same as: x = x // 5 print("After x //= 5:", x) # 4 x **= 3 # same as: x = x ** 3 print("After x **= 3:", x) # 64
Output:
pseudoAfter x += 5: 15 After x -= 3: 12 After x *= 2: 24 After x //= 5: 4 After x **= 3: 64
| Operator | Example | Equivalent To |
|---|---|---|
+= | x += 5 | x = x + 5 |
-= | x -= 5 | x = x - 5 |
*= | x *= 5 | x = x * 5 |
/= | x /= 5 | x = x / 5 |
//= | x //= 5 | x = x // 5 |
%= | x %= 5 | x = x % 5 |
**= | x **= 5 | x = x ** 5 |
2.11 Type Conversion (Casting)
Sometimes you have a value of one type but need it as another type. Python provides functions to convert between types:
python# runnable # String to integer print(int("42")) # 42 print(int("42") + 8) # 50 # String to float print(float("3.14")) # 3.14 # Float to integer (truncates decimal! Not rounding) print(int(3.99)) # 3 (truncated, not rounded) print(int(-2.7)) # -2 (truncated toward zero) # Number to string print(str(42)) # "42" print(str(3.14)) # "3.14" # Converting one type to another num_str = "100" num_int = int(num_str) num_float = float(num_str) print(num_int + 50) # 150 print(num_float + 50) # 150.0
Output:
pseudo42 50 3.14 3 -2 42 3.14 150 150.0
⚠️ Warning:int("3.14")producesValueError: invalid literal for int() with base 10: '3.14'— you can't convert a string with a decimal point directly to int. First convert to float:int(float("3.14")).
2.12 Worked Example 2: Temperature Converter
Let's build a formula that converts Celsius to Fahrenheit:
python# runnable celsius = 100 fahrenheit = celsius * 9 / 5 + 32 print(celsius, "°C =", fahrenheit, "°F") celsius = 0 fahrenheit = celsius * 9 / 5 + 32 print(celsius, "°C =", fahrenheit, "°F") celsius = 37 fahrenheit = celsius * 9 / 5 + 32 print(celsius, "°C =", fahrenheit, "°F")
Output:
pseudo100 °C = 212.0 °F 0 °C = 32.0 °F 37 °C = 98.6 °F
2.13 Worked Example 3: Area and Circumference of a Circle
Area=πr2Circumference=2πrpython# runnable pi = 3.14159 radius = 5 area = pi * radius ** 2 circumference = 2 * pi * radius print("Radius:", radius) print("Area:", area) print("Circumference:", circumference)
Output:
pseudoRadius: 5 Area: 78.53975 Circumference: 31.4159
Line-by-line:
radius ** 2means "radius squared" (radius × radius).pi * radius ** 2follows precedence: exponent happens before multiplication.2 * pi * radiusmultiplies in order: 2 × pi, then × radius.
2.14 Worked Example 4: Simple Interest Calculator
Simple Interest=100P×R×Tpython# runnable principal = 10000 # P: amount borrowed rate = 8.5 # R: annual interest rate in percent time = 3 # T: time in years simple_interest = (principal * rate * time) / 100 total_amount = principal + simple_interest print("Principal: ₹", principal) print("Rate:", rate, "% per year") print("Time:", time, "years") print("Simple Interest: ₹", simple_interest) print("Total Amount: ₹", total_amount)
Output:
pseudoPrincipal: ₹ 10000 Rate: 8.5 % per year Time: 3 years Simple Interest: ₹ 2550.0 Total Amount: ₹ 12550.0
2.15 Worked Example 5: Swapping Values (The Pythonic Way)
python# runnable # Method 1: Using a temporary variable (works in any language) a = 5 b = 10 temp = a a = b b = temp print("a =", a, "b =", b) # Method 2: Python's tuple unpacking (elegant!) x = 5 y = 10 x, y = y, x print("x =", x, "y =", y)
Output:
pseudoa = 10 b = 5 x = 10 y = 5
📐 Key Concepts Reference
| Concept | Syntax | Example | Explanation |
|---|---|---|---|
| Variable assignment | name = value | age = 25 | Stores value in variable |
| Multiple assignment | a, b = 1, 2 | x, y = 10, 20 | Assigns 1 to a, 2 to b |
| Same-value assignment | a = b = c = 0 | a = b = c = 0 | All three get 0 |
| Dynamic typing | x = 5 then x = "Hi" | Python allows type changes | |
| Floor division | // | 10 // 3 → 3 | Division, rounded down |
| Modulus | % | 10 % 3 → 1 | Remainder after division |
| Exponentiation | ** | 2 ** 3 → 8 | 2 raised to power 3 |
| Type conversion | int(), float(), str() | int("42") → 42 | Convert between types |
⚠️ Common Pitfalls
Pitfall 1: Variable Name Starts with a Number
The mistake:
1st_place = "Gold" The error: SyntaxError: invalid decimal literal Why: Python sees 1 and thinks it's a number, then finds st_place and gets confused. Fix: Start with a letter or underscore: first_place = "Gold" or _1st_place = "Gold".Pitfall 2: Using = Instead of == in Conditions
The mistake: Writing
if x = 5: (single =) when you mean if x == 5: (double ==). The error: SyntaxError: invalid syntax. Maybe you meant '==' or ':=' instead of '='? Why: Single = is for assignment, not comparison. Fix: Use == for comparison.Pitfall 3: Confusing int() with Rounding
The mistake:
int(3.99) thinking it gives 4. The result: 3 (not 4!). Why: int() truncates toward zero — it chops off the decimal part. Fix: Use round(3.99) for mathematical rounding (→ 4).Pitfall 4: Trying to Convert Invalid Strings
The mistake:
int("3.14") or int("hello") The error: ValueError: invalid literal for int() with base 10: '3.14' Why: int() expects a string that represents a whole number. Fix: int(float("3.14")) for decimal strings, or use float().📝 Practice Questions
Q1: What will this code output?pythonx = 5 y = x + 2 x = 10 print(y)Answer:pseudo7Wheny = x + 2runs,xis5, soybecomes7. Changingxlater doesn't affecty—yalready has its own value7. Q2: Evaluate the expression step by step:pythonresult = (5 + 3) * 2 ** 2 // 4 - 1 print(result)Answer:pseudo7Step-by-step:
(5 + 3)→82 ** 2→48 * 4→3232 // 4→88 - 1→7Q3: What's the difference between print(10 / 3) and print(10 // 3)?Answer:
10 / 3→3.3333333333333335(true division, returns float)10 // 3→3(floor division, rounds DOWN to nearest integer)Use/when you need the exact decimal value. Use//when you need a whole number (e.g., splitting items into groups). Q4: Why does this code produce an error? Fix it.pythonvalue = "100" result = value + 50 print(result)Answer: Error:TypeError: can only concatenate str (not "int") to strWhy:valueis a string"100". You can't add a string and an integer. Fix: Convert to int:result = int(value) + 50→ outputs150Q5: Find the errors in this variable naming:pythonmy-var = 10 2nd_try = 20 class = 30Answer:
my-var— Invalid: hyphens are not allowed. Usemy_varinstead.2nd_try— Invalid: starts with a digit. Usesecond_tryinstead.class— Invalid:classis a Python keyword. Useclass_nameinstead. Q6: What does this code output and why?pythona, b = 10, 20 a, b = b, a + b print(a, b)Answer:pseudo20 30
- On the second line, Python evaluates the right side FIRST:
bis20,a + bis10 + 20 = 30.- Then it assigns:
a = 20,b = 30. Q7: Write a program that converts a given number of seconds into hours, minutes, and seconds.Answer:python# runnable total_seconds = 3665 hours = total_seconds // 3600 # 1 hour = 3600 seconds minutes = (total_seconds % 3600) // 60 seconds = total_seconds % 60 print(total_seconds, "seconds =", hours, "hours,", minutes, "minutes,", seconds, "seconds")Output:pseudo3665 seconds = 1 hours, 1 minutes, 5 secondsQ8: Predict the output:pythonx = 10 x += 5 x *= 2 x -= 7 x //= 3 print(x)Answer:pseudo7Step by step:
- Start:
x = 10x += 5→x = 15x *= 2→x = 30x -= 7→x = 23x //= 3→x = 7(23 ÷ 3 = 7.666..., floored to 7) Q9: What is the value of 7 % 2 and 7 % 5?Answer:
7 % 2→1(7 ÷ 2 = 3 remainder 1)7 % 5→2(7 ÷ 5 = 1 remainder 2)The modulus operator gives the remainder after division. Think of it as "how many are left over after making as many equal groups as possible." Q10: Write code to check if a number is even or odd using the modulus operator.Answer:python# runnable number = 17 remainder = number % 2 print("Remainder when divided by 2:", remainder) print("Is it even?", remainder == 0)Output:pseudoRemainder when divided by 2: 1 Is it even? FalseIfnumber % 2 == 0, the number is even. Ifnumber % 2 == 1, it's odd. This is one of the most common uses of the modulus operator.
🔗 Cross-References
- Next Topic: Input, Output & Formatted Strings — Getting user input and formatting output with f-strings.
- Previous Topic: Introduction to Programming & Python
- BSCS1001 Computational Thinking: Variables connect to the concept of "state" in computational problems.
- Reference: Python for Everybody, Chapter 2 — "Variables, expressions, and statements"
- Video: L5: Variables & literals in python, L6: Data types part 1 Join Discord Previous1. Intro to ProgrammingNext3. Input & Output