Python Variables and Data Types: A Complete Guide
Variables are the foundation of every Python program. Before you can write a loop, define a function, or build an algorithm, you need a place to store data β and that's exactly what a variable gives you. In this guide you'll learn how to create variables, which data types Python provides, and how to convert between them.
What Is a Variable?
A variable is a named label that points to a value stored in memory. You create one with a simple assignment statement using the = operator:
# Assign a value to a variable
crop_name = "wheat"
plot_count = 12
growth_rate = 1.5
is_irrigated = True
print(crop_name) # wheat
print(plot_count) # 12
Naming rules to keep in mind:
- Use lowercase letters and underscores:
crop_name, notCropNameorcropname. - Names must start with a letter or underscore β never a digit.
- No spaces allowed; use underscores instead.
- Avoid Python's reserved keywords (
if,for,return, etc.).
harvest_yield beat cryptic ones like hy. Your future self will thank you.
Basic Data Types
Python has several built-in types. You don't need to declare them β Python infers the type from the value you assign.
int β integers
Whole numbers, positive or negative, with no decimal point.
gold = 250
plots_owned = 6
seeds_in_bag = -3 # negative ints are valid
print(type(gold)) # <class 'int'>
float β decimal numbers
Numbers with a fractional part. Python uses 64-bit double precision floats.
growth_rate = 1.5
water_level = 0.75
temperature = -2.3
print(type(growth_rate)) # <class 'float'>
str β strings
Text data, enclosed in single or double quotes. Strings are immutable β once created, the characters cannot be changed in place.
crop_name = "wheat"
message = 'Harvest ready!'
multiline = """Season 3
Day 12"""
# String concatenation
greeting = "Hello, " + crop_name + "!"
print(greeting) # Hello, wheat!
# f-strings (the modern way)
info = f"{crop_name} grows at rate {growth_rate}"
print(info) # wheat grows at rate 1.5
bool β booleans
Only two possible values: True or False. Note the capital first letter β Python is case-sensitive.
is_mature = True
is_watered = False
print(type(is_mature)) # <class 'bool'>
print(is_mature and is_watered) # False
print(is_mature or is_watered) # True
None β the absence of a value
None represents "nothing" or "no value yet." It's Python's equivalent of null in other languages.
selected_crop = None # player hasn't chosen yet
if selected_crop is None:
print("Please select a crop first.")
else:
print(f"Planting {selected_crop}.")
Dynamic Typing
Python is dynamically typed, meaning a variable can be reassigned to a value of a completely different type. The variable doesn't have a fixed type β the value does.
score = 100 # int
print(type(score)) # <class 'int'>
score = "high" # now it's a str
print(type(score)) # <class 'str'>
# Check type with isinstance()
value = 3.14
print(isinstance(value, float)) # True
print(isinstance(value, int)) # False
TypeError. Use isinstance() to guard against this.
Type Conversion
You can explicitly convert between types using built-in functions: int(), float(), str(), and bool().
user_input = "42" # from input() β always a string
gold_earned = int(user_input) + 10
print(gold_earned) # 52
price = 9.99
print(int(price)) # 9 (truncates, does NOT round)
print(str(price)) # "9.99"
print(float("3.5")) # 3.5
# bool() β falsy values become False
print(bool(0)) # False
print(bool("")) # False
print(bool(42)) # True
print(bool("wheat")) # True
Multiple Assignment
Python lets you assign multiple variables at once, which keeps code concise.
# Unpack into multiple variables
x, y = 3, 7
plot_x, plot_y = 0, 0
# Swap two variables (no temp variable needed)
x, y = y, x
print(x, y) # 7 3
# Assign the same value to several variables
water = fertilizer = pesticide = 0
Constants Convention
Python has no built-in constant type, but by convention, variables intended to stay fixed are written in UPPER_SNAKE_CASE. This is a signal to other developers β and your future self β not to change the value.
MAX_PLOTS = 64
BASE_GROWTH_RATE = 1.0
GRID_WIDTH = 8
GRID_HEIGHT = 8
SEASON_LENGTH_DAYS = 28
Practical Example: Farm Variables
Here's how you might model a crop plot in GrowBit using everything covered above:
crop_name = "carrot" # str β what's planted
plot_x, plot_y = 2, 5 # int β grid position
growth_days = 3 # int β days since planting
is_mature = False # bool β ready to harvest?
cost = 5 # int β seed cost in gold
sell_value = 15 # int β harvest value in gold
water_level = 0.6 # float β 0.0 to 1.0
# Calculate profit margin
if is_mature:
profit = sell_value - cost
print(f"{crop_name} profit: {profit} gold")
else:
remaining = 5 - growth_days # carrot takes 5 days
print(f"{crop_name} ready in {remaining} day(s).")
Every meaningful piece of game state β position, type, readiness, economics β is captured in a well-named variable with the right type. That's the foundation on which everything else is built.