Python Basics: Variables, Types, and Operators
Variables
A variable is a name that refers to a value stored in memory. You create one with a simple assignment:
message = "Hello"
count = 10
pi = 3.14159
Python is dynamically typed — you do not declare a type when creating a variable. The interpreter figures out the type from the value you assign.
x = 5 # x is an int
x = "five" # x is now a str — perfectly valid
This flexibility is convenient, but it also means you need to keep track of what type each variable holds.
Variable Naming Rules
Python variable names must follow these rules:
- Start with a letter or underscore (
_), never a number - Contain only letters, numbers, and underscores
- Are case-sensitive (
score,Score, andSCOREare three different variables)
# Valid names
user_name = "Alice"
_count = 0
totalPrice2 = 49.99
# Invalid names
# 2nd_place = "Bob" # starts with a number
# my-variable = 10 # hyphens are not allowed
# class = "Math" # 'class' is a reserved keyword
By convention, Python programmers use snake_case for variable and function names: lowercase words separated by underscores. Constants are written in ALL_CAPS:
max_retries = 3
DEFAULT_TIMEOUT = 30
Core Data Types
Python has four fundamental data types you will use constantly.
int — Integers
Whole numbers, positive or negative, with no size limit:
age = 30
population = 8_000_000_000 # underscores improve readability
negative = -42
float — Floating-Point Numbers
Numbers with a decimal point:
temperature = 98.6
ratio = 0.75
tiny = 1.5e-4 # 0.00015
Be aware that floating-point arithmetic can produce small rounding errors:
print(0.1 + 0.2) # 0.30000000000000004
This is not a Python bug — it is a property of how all computers represent decimal fractions in binary. For financial calculations, use the decimal module.
str — Strings
Sequences of characters enclosed in quotes:
first_name = "Ada"
last_name = 'Lovelace'
full_bio = """Ada Lovelace is widely regarded
as the first computer programmer."""
Strings are immutable. Methods like .upper() return a new string rather than modifying the original:
name = "python"
upper_name = name.upper()
print(name) # python (unchanged)
print(upper_name) # PYTHON
bool — Booleans
True or False (capitalized exactly this way):
is_active = True
has_permission = False
Booleans are the result of comparison expressions and drive control flow (covered in the next tutorial).
Type Checking and Conversion
Use type() to inspect a value’s type:
print(type(42)) # <class 'int'>
print(type(3.14)) # <class 'float'>
print(type("hello")) # <class 'str'>
print(type(True)) # <class 'bool'>
Convert between types with int(), float(), str(), and bool():
number_str = "100"
number_int = int(number_str) # 100
number_float = float(number_str) # 100.0
print(str(42)) # "42"
print(bool(0)) # False
print(bool(1)) # True
print(bool("")) # False (empty string is falsy)
print(bool("hi")) # True (non-empty string is truthy)
Arithmetic Operators
a = 15
b = 4
print(a + b) # 19 addition
print(a - b) # 11 subtraction
print(a * b) # 60 multiplication
print(a / b) # 3.75 division (always float)
print(a // b) # 3 floor division
print(a % b) # 3 modulo (remainder)
print(a ** b) # 50625 exponentiation (15^4)
Python also supports augmented assignment operators:
score = 10
score += 5 # same as score = score + 5 → 15
score -= 3 # 12
score *= 2 # 24
score //= 5 # 4
Comparison Operators
Comparisons return a bool:
x = 10
y = 20
print(x == y) # False (equal to)
print(x != y) # True (not equal to)
print(x < y) # True (less than)
print(x > y) # False (greater than)
print(x <= 10) # True (less than or equal to)
print(x >= 15) # False (greater than or equal to)
You can chain comparisons, which reads naturally:
age = 25
print(18 <= age <= 65) # True — age is between 18 and 65 inclusive
String Concatenation
Join strings with the + operator:
first = "Jane"
last = "Doe"
full = first + " " + last
print(full) # Jane Doe
Repeated concatenation uses *:
print("-" * 40) # ----------------------------------------
F-Strings
F-strings (introduced in Python 3.6) are the cleanest way to embed expressions inside strings:
name = "Alice"
age = 30
print(f"{name} is {age} years old.")
# Alice is 30 years old.
You can put any valid expression inside the curly braces:
price = 49.99
tax_rate = 0.08
print(f"Total: ${price * (1 + tax_rate):.2f}")
# Total: $53.99
The :.2f is a format specifier that rounds the result to two decimal places — useful for currency.
items = ["apple", "banana", "cherry"]
print(f"There are {len(items)} items.")
# There are 3 items.
Next Steps
You now have a solid grasp of variables, Python’s core types, and operators. The next tutorial covers control flow: making decisions with if and repeating actions with loops.