Skip to content

Python Variables and Data Types: Beginner Examples and Type Checking

  • by

Python variables are names bound to objects. You create a name by assigning a value with =; you do not declare a variable’s type first. This beginner guide explains assignment, naming rules, built-in types, mutability, and common errors with Python 3 examples you can run.

Creating and printing variables

age = 24
salary = 10000.0
name = "John"
print(age)
print(salary)
print(name)

Output:

24
10000.0
John

age refers to an integer object, salary to a floating-point object, and name to a string. Python is dynamically typed: objects have types, while names can be rebound to objects of different types. The older Python 2 syntax print age is invalid in Python 3.

Multiple assignment and reassignment

name, age, salary = "John", 24, 10000.0
a = "John"
a = 10000.0
print(a)  # 10000.0
x = y = 5
print(x, y)  # 5 5

Multiple assignment evaluates the right-hand expression and assigns its values to the target names in the corresponding positions. In name, age, salary = ..., the first value goes to name, the second to age, and the third to salary. Reassignment binds a name to another object; it does not change the type of the earlier object. Be careful with a = b = []: both names then refer to the same mutable list.

Deleting a variable

count = 100
print(count)  # 100
del count
# print(count)  # NameError: name 'count' is not defined

del count removes the binding in the current scope; it does not necessarily destroy the object if other references exist. A later attempt to read an unbound name raises NameError.

Python variable naming rules

  • Names can contain Unicode letters, digits, and underscores, but cannot begin with a digit.
  • Names are case-sensitive: total and Total differ.
  • Reserved keywords such as class and for cannot be used as names.
  • Prefer descriptive snake_case names for ordinary variables, following PEP 8.
  • Avoid shadowing built-ins such as list, str, and sum.
student_name = "Asha"  # valid
item2 = 7              # valid
# 2item = 7             # SyntaxError
# class = "Math"        # SyntaxError

Built-in Python data types

Numbers: int, float, complex and bool

int stores whole numbers (limited by available memory); float stores finite-precision floating-point values; complex stores real and imaginary components. bool represents True or False and is a subclass of int.

whole = 5
decimal = 5.0
number = 1 + 2j
active = True
for value in (whole, decimal, number, active):
    print(type(value).__name__)

Output:

int
float
complex
bool

Floating-point arithmetic is approximate: 0.1 + 0.2 == 0.3 evaluates to False. Use math.isclose() for approximate comparisons or decimal.Decimal when decimal precision matters.

Sequences: str, list, tuple and range

A str is an immutable sequence of Unicode characters. A list is an ordered, mutable sequence; a tuple is ordered but immutable. A range represents an arithmetic progression of integers.

message = "Hello World"
items = ["I", "am", "007"]
items.append("ready")
print(items[0], items[-1])  # I ready
print(items)  # ['I', 'am', '007', 'ready']
empty = ()
one_item = ("apple",)  # trailing comma is required
fruits = ("Grapes", "Apple")
nested = ((0, 1, 2, 3), ("Apple", "Mango"))
print(one_item)  # ('apple',)
print(nested)    # ((0, 1, 2, 3), ('Apple', 'Mango'))

Parentheses alone do not make a tuple: the comma does. For example, (3) is an integer, while (3,) is a one-item tuple. Both lists and tuples support zero-based indexing and slicing.

Other common types: dict, set, bytes and None

scores = {"Asha": 90, "Ravi": 85}  # dict
unique_ids = {1, 2, 2, 3}        # set: {1, 2, 3}
raw = b"ABC"                     # bytes
missing = None                   # NoneType
print(scores["Asha"])            # 90
print(len(unique_ids))           # 3
print(missing is None)           # True

Dictionaries map hashable keys to values; sets store distinct hashable elements. None represents the absence of a value. Check it with is None, not == None.

Inspecting types and converting values

age_text = "24"
age = int(age_text)
print(type(age).__name__)      # int
print(isinstance(age, int))    # True
print(str(age))                # 24

type() reports an object’s type; isinstance() also recognizes subclasses. Conversion may fail: int("twenty") raises ValueError. Python does not automatically add a number and a string: 2 + "3" raises TypeError.

Mutable versus immutable objects

first = [1, 2]
second = first
second.append(3)
print(first)  # [1, 2, 3]
third = first.copy()
third.append(4)
print(first)  # [1, 2, 3]

Lists and dictionaries are mutable; integers, strings and tuples are immutable. Assignment does not copy an object. A shallow list copy creates a new outer list but still shares nested mutable objects.

Troubleshooting common Python variable errors

  • NameError: check spelling, capitalization and whether the name was assigned in the current scope.
  • SyntaxError: use valid identifiers and Python 3 print(...) syntax.
  • TypeError: check operand types before combining them.
  • ValueError: validate strings before converting with int() or float().
  • Unexpected shared changes: check whether two names reference the same mutable object.

Frequently asked questions

Do Python variables need type declarations?

No. Assignment creates a binding to an object, whose type can be inspected with type(). Optional type hints document intended types but are not enforced by Python at runtime.

Can a Python variable change type?

A name can be rebound from an integer to a string or another object. The original object does not change type.

What is the difference between a list and a tuple?

Both are ordered sequences, but lists can be modified in place and tuples cannot. A tuple can still contain mutable objects.

Further reading

For authoritative definitions and current Python 3 behavior, see the Python tutorial, built-in types reference, and PEP 8 naming conventions. Continue with PickupBrain’s Python operators guide and conditional statements tutorial.

Conclusion

In Python 3, variables are names that reference objects. Learn the difference between mutable and immutable types, use descriptive names, and test small examples to understand assignment and conversion.

Common beginner errors and how to fix them

  • NameError: check that the name was assigned before use and that its spelling and capitalization match.
  • TypeError: do not add a string directly to an integer; convert deliberately with int() or str() when appropriate.
  • Shared mutable values: avoid a = b = [] if you need independent lists. Use a = [] and b = [] instead.
  • Unexpected decimal results: remember that binary floating-point is approximate; use math.isclose() for tolerance-based comparisons.

Practice exercise: predict the output

first = [1, 2]
second = first
second.append(3)
print(first)  # [1, 2, 3]

first = [1, 2]
second = first.copy()
second.append(3)
print(first)  # [1, 2]
print(second)  # [1, 2, 3]

Assignment makes another reference to the same list; list.copy() creates a new outer list. For nested lists, this is a shallow copy, so nested mutable objects may still be shared.

Frequently asked questions

Does Python require a variable declaration?

No. Assign a value to a valid name, such as count = 10. Optional type hints can document intended types, but Python does not enforce them automatically at runtime.

Can a variable change type?

A name can be rebound to an object of another type, such as value = 10 followed by value = "ten". The objects themselves retain their respective types.

How can I check an object’s type?

Use type(value) to inspect its exact class or isinstance(value, int) to test membership in a type hierarchy. Note that isinstance(True, int) is True because bool subclasses int.

Leave a Reply

Your email address will not be published. Required fields are marked *