4.1. Variables and Data Types
Table of Contents
Why Variables and Data Types Matter
Backend code constantly works with information. You receive data in requests, save it to databases, process it, and send it back in responses. To do this safely and predictably, you must:
- Store values in variables
- Know what type each value is
If you ignore types, you get bugs that are painful to debug: wrong calculations, broken comparisons, and crashes.
In this chapter we will stay language agnostic, but examples will look somewhat like Python or JavaScript style pseudocode.
Variables: Names for Values in Memory
A variable is a named box that holds a value in your program's memory.
x = 5
You can read that as: “Create a box called x and put the value 5 into it.”
Creating and Using Variables
Most languages follow this pattern:
# Pseudocode
# Declare and assign
count = 10
# Read the value
print(count) # shows 10
# Change the value
count = count + 1 # now 11In typed languages you often must specify the type:
int count = 10
count = count + 1In more dynamic languages, the type is inferred from the value:
count = 10 # the language decides "this is an integer"Naming Variables
Good variable names make code easier to understand. You will continually read and modify your own code and other people's code, so names matter.
Rules and Conventions
Most languages have similar rules:
- Variable names:
- Must start with a letter or underscore
- Cannot start with a number
- Cannot contain spaces
- Often cannot use special characters like
@,-,/ - They are usually case sensitive
user,User, andUSERare three different variables
Common naming styles:
| Style | Example | Where used |
|---|---|---|
| snake_case | user_name | Python, configuration, many backend scripts |
| camelCase | userName | JavaScript, Java |
| PascalCase | UserName | Class names in many languages |
| SCREAMING_SNAKE_CASE | MAX_RETRIES | Constants |
Good names describe what the variable represents, not how it is used:
# Bad
x = 7
# Better
max_login_attempts = 7Variables vs Constants
A constant is like a variable, but its value should not change after it is set.
# Pseudocode
MAX_CONNECTIONS = 100 # We agree never to reassign thisSome languages let you enforce this:
const MAX_CONNECTIONS = 100 # cannot be changed laterUse constants for values such as:
- Default pagination size
- Timeouts
- Limits on retries
- Application name or version
This reduces accidental changes and makes your intent clear.
Data Types: Kinds of Values
A data type describes what kind of value is stored and what operations are allowed.
Common groups of data types:
- Numbers, integer and floating point
- Text, strings
- True / false, booleans
- Collections, lists, arrays, maps
- Special values, null, none, nil
Important rule
Every value has a type, and operations only make sense when types are compatible.
For example, 5 + 3 is fine, 5 + "hello" is usually an error or produces unexpected results.
Numeric Types
Backend systems use numbers for counts, prices, timestamps, IDs, and more.
Integers
An integer is a whole number, positive, negative, or zero.
user_count = 120
temperature = -5
zero = 0Typical operations:
a = 5
b = 2
sum = a + b # 7
difference = a - b # 3
product = a * b # 10
quotient = a / b # depends on language: 2 or 2.5
remainder = a % b # 1, "modulo"Floating Point Numbers
A floating point number represents real numbers with decimals.
price = 9.99
rating = 4.5
pi = 3.14159Use them for:
- Measurements, 1.75 meters
- Averages and statistics
- Non integer results in calculations
Precision Issues
Floating point numbers are stored in binary, so some decimals are not exact.
Examples in many languages:
0.1 + 0.2 # might give 0.30000000000000004
0.3 == 0.1 + 0.2 # often falseFor money and financial calculations, you usually should not use plain floating point types. Many backend systems use:
- Integers to store cents,
price_cents = 999for $9.99 - Decimal types that keep exact decimal precision
Boolean Type
A boolean has only two values:
truefalse
Examples:
is_admin = true
email_verified = false
has_paid = trueBooleans are crucial for conditions and control flow, which you will use in other chapters like Conditions and Loops.
Typical boolean operations:
has_account = true
has_paid = false
can_login = has_account AND has_paid # falseSome examples of boolean expressions:
age = 20
is_adult = age >= 18 # true
items_in_cart = 0
cart_is_empty = items_in_cart == 0 # trueStrings: Text Data
A string is a sequence of characters, used for text.
name = "Alice"
greeting = 'Hello'
message = "User not found"You work with strings constantly in backends:
- Request paths
/api/users - JSON keys
"email" - Error messages
- SQL queries
- Log messages
Common String Operations
Here are common operations and what they do conceptually:
first_name = "John"
last_name = "Doe"
# Concatenation (joining)
full_name = first_name + " " + last_name # "John Doe"
# Length
len("Backend") # 7 characters
# Access character by index (0 based)
"Backend"[0] # 'B'
"Backend"[3] # 'k'
# Substring
"Backend"[0:4] # "Back" (syntax varies by language)String methods are very common:
"hello".upper() # "HELLO"
"HELLO".lower() # "hello"
" spaced ".strip() # "spaced"
"admin@example.com".ends_with("@example.com") # trueWhen building SQL queries or JSON, you must be very careful with string handling to avoid security issues like SQL injection. That is covered later in the Backend Security and SQL chapters.
Collections: Grouping Values
Backend applications often need to handle many items at once:
- All users in a list
- HTTP headers as key value pairs
- Shopping cart items
- Search results
For that you use collection types.
Lists and Arrays
A list or array is an ordered collection of values, like an ordered row of boxes.
# A list of integers
scores = [10, 20, 30]
# A list of strings
usernames = ["alice", "bob", "charlie"]Typical operations:
numbers = [1, 2, 3]
# Access by index (0 based)
numbers[0] # 1
numbers[2] # 3
# Change a value
numbers[1] = 20 # [1, 20, 3]
# Add an item
numbers.append(4) # [1, 20, 3, 4]
# Length
len(numbers) # 4Lists are useful when:
- Order matters, e.g. log entries in time order
- You might have duplicates, e.g. tags that can repeat
- You often add or remove elements
Maps / Dictionaries / Hash Tables
A map is a collection of key value pairs. In various languages it may be called:
- Dictionary
- Map
- Hash map
- Object (in JavaScript)
Example:
user = {
"id": 123,
"name": "Alice",
"email": "alice@example.com"
}Here:
"id","name","email"are keys123,"Alice","alice@example.com"are values
To read values by key:
user_id = user["id"] # 123
email = user["email"] # "alice@example.com"To add or change:
user["is_admin"] = false # add new key
user["email"] = "alice@newmail.com" # update existingMaps are critical in backend work:
- JSON objects in HTTP requests and responses
- Configuration values
- Environment settings
- Caches
Sets
A set is an unordered collection of unique items.
countries = {"US", "DE", "FR"}
# Adding duplicate has no effect
countries.add("US") # still {"US", "DE", "FR"}Sets are useful when:
- You only care if something is present or not
- You do not care about order
- You want to automatically remove duplicates
Examples for backends:
- User permissions:
{"read_users", "delete_users"} - Feature flags:
{"beta_ui", "logging_v2"}
Null, None, and Missing Values
Sometimes a variable has no value. Many languages use special values for this:
nullNonenilundefined(in some languages)
Use these to mean:
- Value is unknown
- Value is not applicable
- Value has not been set yet
Example:
last_login_at = null # user has never logged inWhen working with null values, you must always be careful:
user = null
# user["name"] # often causes an error, trying to access a property of nullInstead, you check first:
if user is not null:
name = user["name"]
else:
name = "Guest"Static vs Dynamic Typing
Languages differ in how strictly they handle types. As a backend developer you will likely use both kinds over your career.
Statically Typed Languages
In statically typed languages, the type of each variable is known at compile time.
Examples: Java, C#, Go, TypeScript (for frontend but concept applies)
int age = 30
string name = "Alice"
bool is_admin = falseCharacteristics:
- Types are checked before the program runs
- Many type related errors are caught early
- Refactoring is often safer with good tooling
- You usually must declare or let the compiler infer types
Dynamically Typed Languages
In dynamically typed languages, variables do not have fixed types, values do.
Examples: Python, Ruby, JavaScript, PHP
age = 30 # now holds an integer
age = "thirty" # now holds a stringCharacteristics:
- Type is determined at runtime
- Code can be shorter and more flexible
- Some errors only appear when that part of the code runs
- You must be disciplined about how you use variables
Both approaches are heavily used in backend development. Python and JavaScript are common dynamic choices, Go and Java are common static choices.
Type Conversion
Sometimes you must convert from one type to another. This is called type casting or type conversion.
Common Conversions
From string to number:
age_str = "25"
age = int(age_str) # 25
price_str = "9.99"
price = float(price_str) # 9.99From number to string:
user_id = 123
user_id_str = str(user_id) # "123"From string to boolean, usually custom:
value = "true"
is_enabled = (value.lower() == "true") # trueFrom list of pairs to map:
pairs = [["id", 1], ["name", "Alice"]]
user = dict(pairs) # {"id": 1, "name": "Alice"}Implicit vs Explicit Conversion
- Implicit conversion: Language automatically converts types when it can
- Explicit conversion: You manually call conversion functions
Implicit conversions can be convenient, but also dangerous, for example in some languages:
1 + "2" # might become "12" by converting 1 to "1"As a backend developer handling user data, API inputs, and database values, it is usually safer to perform explicit conversions so behavior is clear and predictable.
Practical Backend Examples of Types and Variables
To see how these concepts appear in real backend code, here are some typical patterns in pseudocode.
Storing Request Data
You receive JSON in an HTTP request:
{
"email": "user@example.com",
"age": 25,
"is_admin": false,
"tags": ["new", "beta"]
}You might parse it into variables and proper types:
body = parse_json(request.body)
email = body["email"] # string
age = int(body["age"]) # integer
is_admin = bool(body["is_admin"]) # boolean
tags = body["tags"] # list of stringsBuilding a Response
You collect values from variables and build a response dictionary or map:
user = {
"id": 101,
"email": email,
"age": age,
"is_admin": is_admin,
"tags": tags
}
response_body = to_json(user)Using Types for Validation
You may check types and values to validate an API request:
if type(age) is not int or age < 0:
return error_response("age must be a non-negative integer")
if type(email) is not string or "@" not in email:
return error_response("invalid email")Common Beginner Mistakes with Types and Variables
These issues show up often in backend beginners' code.
| Problem | Example | Why it is bad |
|---|---|---|
| Reusing variable for different types | user = 1, then user = "Alice" | Makes code confusing and error prone |
| Confusing string and number | "10" + 5 | May crash or give "105" instead of 15 |
| Ignoring null / None checks | user["name"] when user might be null | Causes runtime errors in production |
| Using unclear names | x, y, data, temp for important variables | Future you will not understand the code |
| Assuming type from appearance | "00123" looks numeric but may be important as text, e.g. zip codes | Converting may lose leading zeros |
Summary
You have seen:
- Variables are named storage locations for values
- Good variable names and constants improve code clarity
- Data types determine what operations are valid
- Common primitive types are integers, floats, booleans, and strings
- Collections let you group values: lists, maps, and sets
- Null / None represent "no value," and must be handled carefully
- Static and dynamic typing affect when type errors appear
- Type conversion is necessary but must be explicit and careful in backend systems
You will use these concepts in every other chapter, from Conditions and Loops to Databases and REST APIs. Understanding variables and data types now will make the rest of backend development much easier to learn.
Views: 9
KAHIBARO