Python•Variables
Python Variables and Data Types with Examples
In Python, variables are dynamically assigned when you give them a value. Python infers the type automatically at runtime, making data manipulation simple and readable.
Syntax
variable_name = value
Parameters & Values
Key components and acceptable values for this structure:
| Parameter | Type | Description |
|---|---|---|
| variable_name | Identifier | Name of the variable (must start with a letter or underscore). |
| value | Any Python Object | Data assigned to variable (int, float, str, bool, list, etc.). |
Ready-to-Run Code Example
Executable in CompilraRun this complete, working example directly without installing Python locally:
# Python Variables and Types
user_name = "Alex"
user_age = 24
account_balance = 1250.75
is_active = True
print(f"User: {user_name} ({type(user_name).__name__})")
print(f"Age: {user_age} ({type(user_age).__name__})")
print(f"Balance: ${account_balance:.2f} ({type(account_balance).__name__})")
print(f"Active Member: {is_active} ({type(is_active).__name__})")Expected Output:
User: Alex (str) Age: 24 (int) Balance: $1250.75 (float) Active Member: True (bool)
How It Works: Step-by-Step
- Lines 2-5: Assigns values of types string, integer, float, and boolean to variables.
- Lines 7-10: Prints formatted output using f-strings and reveals data types with type().__name__.
Key Concepts
- Line 2 assigns string "Alex" to user_name without type declaration keywords.
- Python infers user_age as int and account_balance as float automatically.
- type() reveals the internal runtime class of each variable.
Common Mistake: Concatenating integers directly with strings using +
In Python, using + between a string and an integer raises a TypeError. Use f-strings or str().
❌ Incorrect
age = 25
print("Age: " + age) # TypeError: can only concatenate str to str✅ Correct
age = 25
print(f"Age: {age}") # Clean string interpolationRelated Python Tutorials & Compiler
Python Operators: Arithmetic, Comparison & Logical
Operators are special symbols that carry out computations on values and variables in Python.
Python Input and Output (I/O) with print() and input()
Learn how to display outputs to the console using print() and receive interactive user input with input().
Python Type Casting and Conversion with Examples
Type casting is the process of converting a variable from one data type into another using Python built-in functions.
Python Online Compiler
Open in Compilra IDE
Run and test Python on Compilra
Execute this code snippet with pre-supplied standard input (stdin) in Compilra’s cloud compiler.