Values vs. Variables: What You Actually Work With
When you write Python code, you are constantly working with values. A value is a piece of data: a number like 42, a word like "hello", a truth value like True, or a collection like [1, 2, 3].
A variable is a name you choose that points to (refers to) a value. Variables help you store values so you can reuse them, change them, and make your code readable.
Think of it like labeling a container: the label (variable name) is not the thing itself (value), but it lets you refer to the thing easily.
x = 10In this line:
xis the variable name=is the assignment operator (it assigns a value to a name)10is the value
Python reads this as: “assign the value 10 to the name x.” It is not a math equation.
Continue in our app.
You can listen to the audiobook with the screen off, receive a free certificate for this course, and also have access to 5,000 other free online courses.
Or continue reading below...Download the app
Reassigning Variables
Variables can be reassigned to new values at any time.
x = 10
x = 25After the second line, x refers to 25, not 10. The old value isn’t “inside” the variable; the name now points somewhere else.
Variables Are Not Boxes (A Helpful Mental Model)
Many beginners imagine a variable as a box that “contains” a value. A more accurate model is: a variable is a label attached to a value. This matters when you start working with lists and other mutable objects, because multiple variables can refer to the same value.
a = [1, 2, 3]
b = aHere, both a and b refer to the same list. If the list changes through one name, you’ll see the change through the other name too.
Core Data Types: The Building Blocks
Python has several core data types you’ll use constantly. Each type represents a different kind of value and supports different operations.
- int: whole numbers (e.g.,
0,-7,2026) - float: decimal numbers (e.g.,
3.14,-0.5) - str: text (strings) (e.g.,
"Python") - bool: truth values (
TrueorFalse) - NoneType: the special value
Nonemeaning “no value” or “not set” - list: ordered, changeable collection (e.g.,
["eggs", "milk"]) - tuple: ordered, usually unchangeable collection (e.g.,
(10, 20)) - dict: key-value mapping (e.g.,
{"name": "Ava", "age": 12}) - set: unordered collection of unique items (e.g.,
{1, 2, 3})
You can check a value’s type using type().
type(10) # int
type(3.14) # float
type("hi") # str
type(True) # boolStep-by-Step: Inspecting Types and Values
Try this sequence to build intuition about values and types:
age = 12
pi = 3.14159
name = "Sam"
is_student = True
nothing_yet = None
print(age, type(age))
print(pi, type(pi))
print(name, type(name))
print(is_student, type(is_student))
print(nothing_yet, type(nothing_yet))Notice how each variable name refers to a value, and each value has a type.
Numbers: int and float
Numbers are used for counting, measuring, and calculations.
int: Whole Numbers
int values have no decimal point.
apples = 5
bananas = 2
total_fruit = apples + bananasCommon operations include:
- Addition:
+ - Subtraction:
- - Multiplication:
* - Integer division (quotient only):
// - Remainder:
% - Exponent:
**
print(7 // 3) # 2
print(7 % 3) # 1
print(2 ** 5) # 32float: Decimal Numbers
float values include a decimal point (even if it’s .0).
price = 2.50
quantity = 3
cost = price * quantity
print(cost) # 7.5When you mix int and float in an operation, Python usually produces a float.
print(5 + 2.0) # 7.0Step-by-Step: A Mini “Change Calculator”
This example shows how numeric types and operators work together.
paid = 20
price = 13
change = paid - price
quarters = change // 25
change = change % 25
dimes = change // 10
change = change % 10
nickels = change // 5
change = change % 5
pennies = change
print(quarters, dimes, nickels, pennies)This script uses // and % to break down a number into parts. (If you want realistic money handling, you often store cents as integers to avoid floating-point rounding issues.)
Text: str (Strings)
A string is text. In Python, strings are written in quotes: single quotes ' ' or double quotes " ". Both work; choose one style and be consistent.
greeting = "Hello"
name = 'Mina'Combining Strings
You can combine strings using + (concatenation).
full = greeting + ", " + name
print(full)Be careful: + does not automatically convert numbers to strings.
age = 12
# print("Age: " + age) # This would cause an errorConvert the number first using str():
print("Age: " + str(age))f-strings: Clean String Formatting
f-strings are a beginner-friendly way to insert values into text.
age = 12
print(f"{name} is {age} years old")Inside the curly braces, you can put variables or even expressions.
width = 5
height = 3
print(f"Area: {width * height}")Useful String Basics
- Length with
len() - Indexing to get a character (starts at 0)
- Slicing to get part of a string
word = "Python"
print(len(word)) # 6
print(word[0]) # P
print(word[1:4]) # yth
print(word[-1]) # nStrings are immutable, meaning you can’t change them in place. If you “modify” a string, you are actually creating a new string.
word = "cat"
word = word + "s" # creates a new string "cats"Step-by-Step: Cleaning User Text
Text often needs cleaning. Here is a practical sequence using common string methods:
raw = " Ada Lovelace "
clean = raw.strip() # remove spaces at both ends
lower = clean.lower() # make lowercase
upper = clean.upper() # make uppercase
print(clean)
print(lower)
print(upper)Methods like strip(), lower(), and upper() return new strings.
True/False: bool
A boolean is either True or False. Booleans are essential for decision-making and conditions.
is_raining = False
has_umbrella = TrueBooleans often come from comparisons:
print(10 > 3) # True
print(5 == 5) # True
print(5 != 5) # False
print(2 <= 1) # FalseAnd can be combined with logical operators:
and: both must be trueor: at least one must be truenot: flips true/false
age = 12
has_ticket = True
can_enter = (age >= 12) and has_ticket
print(can_enter)Truthiness: Values That Behave Like True/False
In conditions, Python treats some values as “truthy” or “falsy.” This is useful, but you should understand it clearly.
- Falsy:
0,0.0,"",[],{},set(),None - Truthy: most other values
name = ""
if name:
print("Name provided")
else:
print("Name is empty")The Special Value None
None represents “no value yet” or “unknown.” It is commonly used as a placeholder.
best_score = NoneYou often check for None using is (not ==).
if best_score is None:
print("No score recorded yet")None is not the same as 0 or "". Those are real values; None means “nothing here.”
Collections: list, tuple, dict, set
Collections hold multiple values. Choosing the right collection type makes your code simpler and safer.
list: Ordered and Changeable
A list is an ordered collection you can modify (add, remove, replace items).
shopping = ["milk", "bread", "eggs"]
shopping.append("apples")
shopping[0] = "oat milk"
print(shopping)Lists are great when:
- Order matters
- You need to add/remove items
- You may have duplicates
Common list operations:
numbers = [10, 20, 30]
print(len(numbers))
print(numbers[1])
print(numbers[0:2])
numbers.remove(20)
print(numbers)Step-by-Step: Tracking Daily Temperatures
This example shows how a list can store changing data.
temps = []
temps.append(21.5)
temps.append(19.0)
temps.append(23.25)
average = sum(temps) / len(temps)
print(f"Readings: {temps}")
print(f"Average: {average}")The list starts empty, then grows as you append readings.
tuple: Ordered and Usually Unchangeable
A tuple is like a list, but you typically don’t change it. This makes tuples good for fixed groups of values, such as coordinates.
point = (3, 7)
print(point[0])Tuples are useful when:
- You want a fixed structure
- You want to signal “do not modify this”
Python also uses tuples in multiple assignment (unpacking):
x, y = (3, 7)
print(x)
print(y)dict: Key-Value Pairs
A dictionary maps keys to values. Use it when you want to look up information by a name or identifier.
student = {"name": "Kai", "age": 12, "grade": 7}
print(student["name"])You can add or update entries by assigning to a key:
student["age"] = 13
student["city"] = "Oslo"To safely access a key that might not exist, use get():
nickname = student.get("nickname")
print(nickname) # None if missingStep-by-Step: Counting Items with a Dictionary
Counting is a common real-world task. Here is a clear approach:
words = ["red", "blue", "red", "green", "blue", "red"]
counts = {}
for w in words:
if w in counts:
counts[w] = counts[w] + 1
else:
counts[w] = 1
print(counts)This builds a dictionary where each word is a key and the value is how many times it appears.
set: Unique Items
A set stores unique values (no duplicates). Sets are useful for membership tests and removing duplicates.
colors = {"red", "blue", "red"}
print(colors) # duplicates removedMembership checks are fast and readable:
allowed = {"admin", "editor"}
role = "viewer"
print(role in allowed) # FalseType Conversion (Casting): Turning One Type into Another
Sometimes you need to convert values between types. Common conversions include:
int("123")converts a numeric string to an integerfloat("3.14")converts a numeric string to a floatstr(123)converts a number to textbool(value)converts a value toTrue/Falsebased on truthiness
text_age = "12"
age = int(text_age)
print(age + 1) # 13Be careful: conversion can fail if the text is not in the right format.
# int("twelve") would cause an errorStep-by-Step: Reading Input and Converting It
input() always returns a string. If you want a number, you must convert it.
text = input("Enter a number: ")
number = int(text)
print(number * 2)If the user types something that isn’t a whole number, int() will fail. Later, you can learn to handle that with error handling, but the key idea here is: input starts as str.
Mutability: Why Some Values “Change” and Others Don’t
One of the most important ideas for beginners is mutability.
- Immutable types cannot be changed in place:
int,float,str,bool,tuple - Mutable types can be changed in place:
list,dict,set
This affects how variables behave when multiple names refer to the same value.
Example: Immutable (int)
a = 10
b = a
b = b + 1
print(a) # 10
print(b) # 11b = b + 1 creates a new integer value and reassigns b. It does not change a.
Example: Mutable (list)
a = [1, 2]
b = a
b.append(3)
print(a) # [1, 2, 3]
print(b) # [1, 2, 3]Because the list is mutable, modifying it through b also affects what a refers to (the same list).
Step-by-Step: Making a Real Copy of a List
If you want a separate list, make a copy.
a = [1, 2]
b = a.copy()
b.append(3)
print(a) # [1, 2]
print(b) # [1, 2, 3]Now a and b refer to different lists.
Naming Variables: Clarity Beats Cleverness
Good variable names make code easier to understand. Use names that describe what the value represents.
- Prefer
total_priceovertp - Prefer
student_countoversc - Avoid using built-in names like
list,dict,stras variable names
Python variable names commonly use snake_case (lowercase with underscores).
total_seconds = 125
minutes = total_seconds // 60
seconds = total_seconds % 60
print(f"{minutes} minutes and {seconds} seconds")Putting It Together: A Small Useful Script Using Multiple Types
This script combines strings, numbers, booleans, and a dictionary to store and display simple profile data.
Step-by-Step: Build a Simple Profile Record
Step 1: Collect input (strings at first).
name = input("Name: ")
age_text = input("Age: ")
city = input("City: ")Step 2: Convert age to an integer so you can do numeric comparisons.
age = int(age_text)Step 3: Create a boolean based on a rule (for example, whether the person is a teen).
is_teen = (age >= 13) and (age <= 19)Step 4: Store everything in a dictionary for easy access by key.
profile = {
"name": name,
"age": age,
"city": city,
"is_teen": is_teen
}Step 5: Display a friendly message using an f-string.
print(f"Profile: {profile['name']} ({profile['age']}) from {profile['city']}")
print(f"Teen: {profile['is_teen']}")This example shows a common pattern: input starts as strings, you convert what needs to be numeric, you compute booleans from comparisons, and you store related data in a dictionary.