Variables and Data Types
Learn about Python variables, data types, type casting, and dynamic typing. A comprehensive guide for beginners.
Variables and Data Types in Python
Python is a dynamically typed language, meaning you donβt need to explicitly declare variable types. The interpreter infers the type based on the assigned value.
Creating Variables
In Python, variables are created the moment you assign a value:
# String variable
name = "Alice"
# Integer variable
age = 30
# Float variable
height = 5.9
# Boolean variable
is_student = True
Data Types
Python has several built-in data types:
Numeric Types
| Type | Description | Example |
|---|---|---|
int | Integer numbers | 42 |
float | Floating point | 3.14 |
complex | Complex numbers | 3+4j |
Text Type
message = "Hello, World!"
multiline = """This is a
multiline string."""
Sequence Types
- List: Ordered, mutable collection β
[1, 2, 3] - Tuple: Ordered, immutable collection β
(1, 2, 3) - Range: Sequence of numbers β
range(0, 10)
Type Checking
Use type() to check a variableβs type:
x = 42
print(type(x)) # <class 'int'>
y = 3.14
print(type(y)) # <class 'float'>
Type Casting
Convert between types using built-in functions:
# String to Integer
num = int("42")
# Integer to Float
decimal = float(42)
# Number to String
text = str(3.14)
Best Practices
- Use descriptive variable names (
user_countnotuc) - Follow snake_case naming convention
- Use constants in UPPER_CASE (
MAX_RETRIES = 3) - Avoid single-letter variables except in loops
Tip: Python 3.10+ supports structural pattern matching, which can simplify type-based logic.
Related Articles
Loops in Python
Master for loops, while loops, loop control statements, and advanced iteration patterns in Python.
Introduction to C++
Getting started with C++ programming β compiler setup, basic syntax, variables, and your first program.
Classes and Objects
Understanding object-oriented programming in Python with classes, objects, inheritance, and encapsulation.