Beginner

Variables & Data Types

Learn how Python stores data in variables, the core data types, type conversion, string formatting, and math operators.

Variables and Assignment

In Python, you create a variable simply by assigning a value to a name. No type declaration is needed — Python figures out the type automatically (dynamic typing).

Python
# Variable assignment
name = "Alice"
age = 30
height = 5.7
is_student = True

# Multiple assignment
x, y, z = 1, 2, 3

# Same value to multiple variables
a = b = c = 0
💡
Naming rules: Variable names must start with a letter or underscore, can contain letters, numbers, and underscores, and are case-sensitive. Use snake_case for variables (e.g., user_name, total_count).

Core Data Types

TypeDescriptionExample
intInteger (whole number)42, -7, 0
floatFloating-point (decimal)3.14, -0.5, 1e10
strString (text)"hello", 'world'
boolBooleanTrue, False
NoneTypeRepresents absence of valueNone
Python
# Integers - unlimited precision in Python
count = 42
big_number = 1_000_000  # Underscores for readability

# Floats - double-precision floating point
pi = 3.14159
scientific = 2.5e-3  # 0.0025

# Strings - single or double quotes
greeting = "Hello, World!"
multiline = """This string
spans multiple
lines."""

# Booleans
is_active = True
is_deleted = False

# None - represents "nothing" or "no value"
result = None

Type Conversion

Convert between types using built-in functions:

Python
# String to integer
num_str = "42"
num = int(num_str)      # 42

# Integer to float
x = float(10)           # 10.0

# Number to string
s = str(3.14)            # "3.14"

# String to boolean
bool("hello")            # True (non-empty)
bool("")                 # False (empty)
bool(0)                  # False
bool(42)                 # True

String Operations

Python
text = "Hello, Python!"

# Indexing (0-based)
print(text[0])        # H
print(text[-1])       # !

# Slicing [start:end:step]
print(text[0:5])      # Hello
print(text[::2])      # Hlo yhn
print(text[::-1])     # !nohtyP ,olleH

# String methods
print(text.upper())       # HELLO, PYTHON!
print(text.lower())       # hello, python!
print(text.replace("Python", "World"))
print(text.split(", "))    # ['Hello', 'Python!']
print(" - ".join(["a", "b", "c"]))  # a - b - c
print(text.strip())       # Remove whitespace
print(text.find("Python")) # 7 (index)
print(len(text))           # 14

String Formatting (f-strings)

F-strings (formatted string literals) are the modern, preferred way to format strings in Python 3.6+:

Python
name = "Alice"
age = 30
price = 49.99

# f-string (recommended)
print(f"Name: {name}, Age: {age}")

# Expressions inside f-strings
print(f"Next year: {age + 1}")

# Formatting numbers
print(f"Price: ${price:.2f}")       # Price: $49.99
print(f"Big: {1000000:,}")          # Big: 1,000,000
print(f"Percent: {0.856:.1%}")     # Percent: 85.6%

# Older methods (still valid)
print("Name: {}, Age: {}".format(name, age))
print("Name: %s, Age: %d" % (name, age))

Numbers and Math Operators

OperatorDescriptionExampleResult
+Addition10 + 313
-Subtraction10 - 37
*Multiplication10 * 330
/Division (float)10 / 33.333...
//Floor division10 // 33
%Modulus10 % 31
**Exponentiation2 ** 101024

Type Checking

Python
x = 42
name = "Alice"

# type() returns the type
print(type(x))       # <class 'int'>
print(type(name))    # <class 'str'>

# isinstance() checks type (preferred)
print(isinstance(x, int))        # True
print(isinstance(x, (int, float))) # True (check multiple)
print(isinstance(name, str))     # True
Best practice: Prefer isinstance() over type() for type checking, because it also works with inheritance (subclasses).