Quiz 2

Variables, Data Types & Expressions

2980 words
15 min read
Python Week 1: the first filter for runtime behavior
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:
  1. Create variables and assign values to them
  2. Follow Python's rules for naming variables
  3. Understand dynamic typing — how a variable's type can change
  4. Write arithmetic expressions using operators
  5. Use assignment operators (+=, -=, etc.) as shortcuts
  6. Convert between data types using int(), float(), str()

📋 Prerequisites


📖 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)
  • 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:
pseudo
Alice
25
5.6
True
Line-by-line:
  • name = "Alice" — Python creates a box labeled name and puts the string "Alice" in it.
  • age = 25 — Creates a box labeled age with the integer 25.
  • When we print(name), Python looks in the box labeled name, finds "Alice", and displays it.

2.4 Variable Naming Rules

Python has strict rules for valid variable names:
RuleExamplesWhy?
Start with a letter or underscorename_count1stPython uses the first character to decide if it's a variable name or a number
Remaining: letters, digits, underscoremy_var2my-varmy varOnly alphanumeric and underscore are allowed
Case-sensitiveAge, age, AGE are three different variablesPython distinguishes uppercase and lowercase
Can't be a Python keywordifforwhileKeywords are reserved for Python's syntax
Python keywords you cannot use as variable names:
sql
and, 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:
pseudo
10 20 30
0 0 0
m = 10 n = 5

2.7 Arithmetic Operators

Python supports all the standard arithmetic operations:
OperatorOperationExampleResultExplanation
+Addition10 + 313Adds two numbers
-Subtraction10 - 37Subtracts right from left
*Multiplication10 * 330Multiplies two numbers
/Division10 / 33.333...Always returns a float
//Floor division10 // 33Divides and rounds DOWN to nearest integer
%Modulus (remainder)10 % 31Returns remainder of division
**Exponentiation10 ** 31000Left 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:
pseudo
a + 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:
pseudo
14
20
2
15.0
80
Pro tip: When in doubt, use parentheses () to make your intention clear. It's better to write (2 + 3) * 4 than 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:
pseudo
After x += 5: 15
After x -= 3: 12
After x *= 2: 24
After x //= 5: 4
After x **= 3: 64
OperatorExampleEquivalent To
+=x += 5x = x + 5
-=x -= 5x = x - 5
*=x *= 5x = x * 5
/=x /= 5x = x / 5
//=x //= 5x = x // 5
%=x %= 5x = x % 5
**=x **= 5x = 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:
pseudo
42
50
3.14
3
-2
42
3.14
150
150.0
⚠️ Warning: int("3.14") produces ValueError: 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:
F=C×95+32F = C \times \frac{9}{5} + 32
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:
pseudo
100 °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πr\text{Area} = \pi r^2 \quad \text{Circumference} = 2\pi r
python
# runnable
pi = 3.14159
radius = 5
area = pi * radius ** 2
circumference = 2 * pi * radius
print("Radius:", radius)
print("Area:", area)
print("Circumference:", circumference)
Output:
pseudo
Radius: 5
Area: 78.53975
Circumference: 31.4159
Line-by-line:
  • radius ** 2 means "radius squared" (radius × radius).
  • pi * radius ** 2 follows precedence: exponent happens before multiplication.
  • 2 * pi * radius multiplies in order: 2 × pi, then × radius.

2.14 Worked Example 4: Simple Interest Calculator

Simple Interest=P×R×T100\text{Simple Interest} = \frac{P \times R \times T}{100}
python
# 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:
pseudo
Principal: ₹ 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:
pseudo
a = 10 b = 5
x = 10 y = 5

📐 Key Concepts Reference

ConceptSyntaxExampleExplanation
Variable assignmentname = valueage = 25Stores value in variable
Multiple assignmenta, b = 1, 2x, y = 10, 20Assigns 1 to a, 2 to b
Same-value assignmenta = b = c = 0a = b = c = 0All three get 0
Dynamic typingx = 5 then x = "Hi"Python allows type changes
Floor division//10 // 33Division, rounded down
Modulus%10 % 31Remainder after division
Exponentiation**2 ** 382 raised to power 3
Type conversionint(), float(), str()int("42")42Convert 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?
python
x = 5
y = x + 2
x = 10
print(y)
Answer:
pseudo
7
When y = x + 2 runs, x is 5, so y becomes 7. Changing x later doesn't affect yy already has its own value 7. Q2: Evaluate the expression step by step:
python
result = (5 + 3) * 2 ** 2 // 4 - 1
print(result)
Answer:
pseudo
7
Step-by-step:
  1. (5 + 3)8
  2. 2 ** 24
  3. 8 * 432
  4. 32 // 48
  5. 8 - 17 Q3: What's the difference between print(10 / 3) and print(10 // 3)?
Answer:
  • 10 / 33.3333333333333335 (true division, returns float)
  • 10 // 33 (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.
python
value = "100"
result = value + 50
print(result)
Answer: Error: TypeError: can only concatenate str (not "int") to str Why: value is a string "100". You can't add a string and an integer. Fix: Convert to int: result = int(value) + 50 → outputs 150 Q5: Find the errors in this variable naming:
python
my-var = 10
2nd_try = 20
class = 30
Answer:
  • my-varInvalid: hyphens are not allowed. Use my_var instead.
  • 2nd_tryInvalid: starts with a digit. Use second_try instead.
  • classInvalid: class is a Python keyword. Use class_name instead. Q6: What does this code output and why?
python
a, b = 10, 20
a, b = b, a + b
print(a, b)
Answer:
pseudo
20 30
  • On the second line, Python evaluates the right side FIRST: b is 20, a + b is 10 + 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:
pseudo
3665 seconds = 1 hours, 1 minutes, 5 seconds
Q8: Predict the output:
python
x = 10
x += 5
x *= 2
x -= 7
x //= 3
print(x)
Answer:
pseudo
7
Step by step:
  • Start: x = 10
  • x += 5x = 15
  • x *= 2x = 30
  • x -= 7x = 23
  • x //= 3x = 7 (23 ÷ 3 = 7.666..., floored to 7) Q9: What is the value of 7 % 2 and 7 % 5?
Answer:
  • 7 % 21 (7 ÷ 2 = 3 remainder 1)
  • 7 % 52 (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:
pseudo
Remainder when divided by 2: 1
Is it even? False
If number % 2 == 0, the number is even. If number % 2 == 1, it's odd. This is one of the most common uses of the modulus operator.

🔗 Cross-References

Document outline

Keep your place and jump directly to a heading.

Table of Contents
System Normal // Awaiting Context

Intelligence Hub

Navigate the knowledge graph to generate context. The Hub adapts dynamically to surface backlinks, related notes, and metadata insights.