Python:Python Variables and Data Types with Examples
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:

ParameterTypeDescription
variable_nameIdentifierName of the variable (must start with a letter or underscore).
valueAny Python ObjectData assigned to variable (int, float, str, bool, list, etc.).

Ready-to-Run Code Example

Executable in Compilra

Run 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 interpolation

Related Python Tutorials & Compiler

Run and test Python on Compilra

Execute this code snippet with pre-supplied standard input (stdin) in Compilra’s cloud compiler.

Python Online Compiler