Python Programming Variables & Data Types
Naming Rules 8 Data Types

Python Variables and Data Types Complete Guide

Learn Python variables naming rules, all data types with practical examples, type checking, and type conversion. Essential concepts for Python programming.

Variables

Naming rules & assignment

8 Data Types

Complete reference

Type Checking

type() & isinstance()

Type Conversion

int(), str(), float()

What are Variables in Python?

Variables are named memory locations used to store data in Python. Python is dynamically typed, meaning you don't need to declare variable types explicitly.

Key Concept

In Python, variables are created when you assign a value to them. The variable type is determined automatically based on the assigned value.

Variable Creation Examples
# Variable declaration and assignment
name = "John Doe"        # String variable
age = 25                 # Integer variable
price = 19.99            # Float variable
is_student = True        # Boolean variable

# Multiple assignment
x, y, z = 10, 20, 30

# Same value to multiple variables
a = b = c = 100

# Dynamic typing - change variable type
variable = 10           # Initially integer
print(type(variable))   # 

variable = "Hello"      # Now string
print(type(variable))   # 
Memory Representation

Variables point to memory locations containing values:

name
→ 0x1000
"John Doe"
age
→ 0x1008
25
price
→ 0x1010
19.99

Python Variable Naming Rules

Python has specific rules for naming variables. Following these rules ensures your code is readable and error-free.

Variable Naming Rules List

  1. Can contain letters (a-z, A-Z), digits (0-9), and underscores (_)

    Examples: name1, first_name, Age2024

  2. Must start with a letter or underscore (_), NOT with a digit

    Valid: name, _private, var1
    Invalid: 1var, 2nd_value

  3. Case-sensitive: age, Age, and AGE are different variables

    name = "John" is different from Name = "Jane"

  4. Cannot use Python keywords as variable names

    Cannot use: if, for, while, class, def, etc.

  5. Should be descriptive and meaningful

    Good: student_name, total_price
    Bad: a, x1, temp

  6. Use snake_case for multi-word variables (convention)

    Recommended: first_name, user_age, is_valid_user
    Not recommended: firstName, UserName (camelCase)

  7. Avoid using single characters except for loop counters

    Acceptable in loops: for i in range(10):
    Otherwise use: index, counter

Valid vs Invalid Variable Names
# VALID variable names
name = "John"
first_name = "Jane"
age_2024 = 25
_student = True
MAX_VALUE = 100  # Constants (convention)
user2 = "active"

# INVALID variable names (will cause errors)
# 2name = "John"      # Starts with digit
# first-name = "Jane" # Contains hyphen
# class = "Python"    # Python keyword
# $price = 19.99      # Special character
# user name = "John"  # Contains space
Best Practices:
  • Use descriptive names: student_age instead of sa
  • Use snake_case for variables: first_name
  • Use UPPERCASE for constants: PI = 3.14159
  • Avoid single letters except in loops
  • Don't use reserved keywords

Python Data Types Complete Reference

Python has built-in data types categorized as Numeric, Sequence, Mapping, Set, and Boolean. Understanding these is fundamental to Python programming.

Python is Dynamically Typed

Python automatically determines data types. Use type() function to check any variable's type.

Python Data Types Reference Table

Data Type Type Class Category Description Example Mutable?
int int Numeric Integer numbers (positive, negative, zero) - No size limit age = 25 Immutable
float float Numeric Floating-point numbers (decimal) - 64-bit precision price = 19.99 Immutable
complex complex Numeric Complex numbers with real and imaginary parts z = 3 + 5j Immutable
str str Sequence Text/String data - Sequence of Unicode characters name = "Python" Immutable
list list Sequence Ordered, mutable collection - Allows duplicates numbers = [1, 2, 3] Mutable
tuple tuple Sequence Ordered, immutable collection - Faster than lists coords = (10, 20) Immutable
dict dict Mapping Key-value pairs - Unordered, key must be immutable person = {"name": "John", "age": 30} Mutable
set set Set Unordered collection of unique items unique = {1, 2, 3} Mutable
frozenset frozenset Set Immutable version of set fset = frozenset([1, 2, 3]) Immutable
bool bool Boolean Logical values - True or False (capital T and F) is_valid = True Immutable
NoneType NoneType Special Represents absence of value - Similar to null in other languages result = None Immutable
bytes bytes Binary Immutable sequence of bytes (0-255) data = b"hello" Immutable
bytearray bytearray Binary Mutable sequence of bytes data = bytearray(b"hello") Mutable
Immutable Types
  • int, float, complex
  • str (strings)
  • tuple
  • frozenset
  • bool
  • bytes

Cannot be changed after creation

Mutable Types
  • list
  • dict
  • set
  • bytearray

Can be modified after creation

Identifying Variable Types

Python provides built-in functions to check and identify variable types. This is essential for debugging and type validation.

Using type() and isinstance() Functions

Type Checking Examples
# Different variable types
name = "Python"           # str
age = 25                  # int
price = 19.99             # float
is_valid = True           # bool
numbers = [1, 2, 3]       # list
person = {"name": "John"} # dict

# Using type() function
print(type(name))        # 
print(type(age))         # 
print(type(price))       # 
print(type(is_valid))    # 
print(type(numbers))     # 
print(type(person))      # 

# Compare types directly
print(type(name) == str)   # True
print(type(age) == int)    # True
print(type(price) == float)# True

# Using isinstance() - better for inheritance
print(isinstance(name, str))     # True
print(isinstance(age, int))      # True
print(isinstance(price, float))  # True
print(isinstance(price, (int, float)))  # True (multiple types)

# Check if variable is mutable/immutable
print(isinstance(numbers, list))  # True
print(hasattr(numbers, 'append')) # True (list has append method)
type() Function
  • Returns exact type of object
  • Syntax: type(variable)
  • Returns: <class 'type_name'>
  • Use for exact type matching
  • Example: type(10) == int
isinstance() Function
  • Checks if object is instance of type
  • Syntax: isinstance(variable, type)
  • Returns: True/False
  • Better for inheritance checking
  • Example: isinstance(10, int)
Practical Type Checking Function
def check_variable_type(var, var_name):
    """Check and display variable type information"""
    var_type = type(var)
    
    print(f"Variable: {var_name}")
    print(f"Value: {var}")
    print(f"Type: {var_type}")
    print(f"Type name: {var_type.__name__}")
    
    # Check specific types
    if isinstance(var, int):
        print("✓ This is an integer")
    elif isinstance(var, float):
        print("✓ This is a float")
    elif isinstance(var, str):
        print(f"✓ This is a string with {len(var)} characters")
    elif isinstance(var, list):
        print(f"✓ This is a list with {len(var)} items")
    elif isinstance(var, dict):
        print(f"✓ This is a dictionary with {len(var)} keys")
    
    print("-" * 40)

# Test the function
check_variable_type(42, "answer")
check_variable_type(3.14, "pi")
check_variable_type("Hello Python", "greeting")
check_variable_type([1, 2, 3], "numbers")
check_variable_type({"name": "John", "age": 30}, "person")

Type Conversion in Python

Python allows converting between different data types using built-in functions. This is also called type casting.

Important: Not all type conversions are possible. Converting incompatible types will raise errors.
Common Type Conversion Functions
# Type conversion examples
# int() - converts to integer
x = int(3.14)      # 3 (truncates decimal)
y = int("100")     # 100
# z = int("hello") # ValueError

# float() - converts to float
a = float(10)      # 10.0
b = float("3.14")  # 3.14
c = float("100")   # 100.0

# str() - converts to string
s1 = str(100)      # "100"
s2 = str(3.14)     # "3.14"
s3 = str([1,2,3])  # "[1, 2, 3]"

# list() - converts to list
lst1 = list("hello")        # ['h', 'e', 'l', 'l', 'o']
lst2 = list((1, 2, 3))      # [1, 2, 3]
lst3 = list({1, 2, 3})      # [1, 2, 3]

# tuple() - converts to tuple
t1 = tuple([1, 2, 3])       # (1, 2, 3)
t2 = tuple("hello")         # ('h', 'e', 'l', 'l', 'o')

# set() - converts to set (removes duplicates)
s1 = set([1, 2, 2, 3, 3])   # {1, 2, 3}
s2 = set("hello")           # {'h', 'e', 'l', 'o'}

# dict() - converts to dictionary
# dict requires sequence of (key, value) pairs
d = dict([("a", 1), ("b", 2)])  # {'a': 1, 'b': 2}

# bool() - converts to boolean
b1 = bool(10)      # True (non-zero)
b2 = bool(0)       # False
b3 = bool("")      # False (empty string)
b4 = bool("Hello") # True (non-empty string)
b5 = bool([])      # False (empty list)
b6 = bool([1,2])   # True (non-empty list)

Type Conversion Table

From Type To Type Function Example Notes
String Integer int() int("100") → 100 String must contain valid integer
String Float float() float("3.14") → 3.14 String must contain valid float
Integer/Float String str() str(100) → "100" Always works
Float Integer int() int(3.99) → 3 Truncates decimal (not rounds)
List/Tuple Set set() set([1,2,2]) → {1,2} Removes duplicates
String List list() list("hi") → ['h','i'] Splits into characters

Practice Examples

Try these examples to reinforce your understanding of Python variables and data types.

Interactive Practice Script
# Variables and Data Types Practice
# Run this script and observe the output

# 1. Variable declaration and type checking
print("=== Example 1: Basic Variables ===")
name = "Alice"
age = 30
height = 5.6
is_programmer = True

print(f"Name: {name}, Type: {type(name)}")
print(f"Age: {age}, Type: {type(age)}")
print(f"Height: {height}, Type: {type(height)}")
print(f"Is Programmer: {is_programmer}, Type: {type(is_programmer)}")

# 2. Type conversion
print("\n=== Example 2: Type Conversion ===")
number_str = "100"
number_int = int(number_str)
print(f"String '{number_str}' → Integer: {number_int}")

pi_str = "3.14159"
pi_float = float(pi_str)
print(f"String '{pi_str}' → Float: {pi_float}")

# 3. List operations
print("\n=== Example 3: Lists ===")
fruits = ["apple", "banana", "cherry"]
print(f"Fruits list: {fruits}")
print(f"Type: {type(fruits)}")
print(f"First fruit: {fruits[0]}")

# Add new fruit
fruits.append("orange")
print(f"After adding orange: {fruits}")

# 4. Dictionary example
print("\n=== Example 4: Dictionary ===")
student = {
    "name": "Bob",
    "age": 22,
    "courses": ["Math", "Science", "English"]
}
print(f"Student dictionary: {student}")
print(f"Type: {type(student)}")
print(f"Student name: {student['name']}")
print(f"Student courses: {student['courses']}")

# 5. Set operations (unique values)
print("\n=== Example 5: Sets ===")
numbers = {1, 2, 2, 3, 3, 4, 5}
print(f"Original numbers (with duplicates): [1, 2, 2, 3, 3, 4, 5]")
print(f"Set (duplicates removed): {numbers}")
print(f"Type: {type(numbers)}")

print("\n=== Try It Yourself ===")
print("Modify the values and add your own variables!")
print("Use type() to check different variable types")

Key Takeaways

  • Python variables are dynamically typed - no need to declare types
  • Variable names must follow specific rules: letters, digits, underscores, start with letter/_
  • Python has 8 main data types: int, float, str, list, tuple, dict, set, bool
  • Use type() to check variable type, isinstance() for type checking with inheritance
  • Mutable types (list, dict, set) can be modified after creation
  • Immutable types (int, float, str, tuple) cannot be changed
  • Type conversion functions: int(), float(), str(), list(), etc.
  • Always use descriptive variable names following snake_case convention
Next Topics: Learn about Type Conversion in detail - converting between different data types in Python