Variables and Data Types
Variables are how you store and work with data in Python. Unlike many languages, Python doesn't require you to declare a variable's type — it figures it out automatically.
Creating Variables
Just use = to assign a value to a name:
python
message = "Hello" count = 42 temperature = 98.6 is_active = True
Python Playground
Output
Click "Run" to execute your codeNaming Rules
Variable names in Python:
- Must start with a letter or underscore (
_) - Can contain letters, numbers, and underscores
- Are case-sensitive (
nameandNameare different) - Cannot be Python keywords (
if,for,class, etc.)
By convention, Python uses snake_case for variable names:
python
first_name = "Alice" # Good firstName = "Alice" # Works, but not Pythonic
Data Types
Python has several built-in data types:
| Type | Example | Description |
|---|---|---|
int |
42 |
Whole numbers |
float |
3.14 |
Decimal numbers |
str |
"hello" |
Text strings |
bool |
True / False |
Boolean values |
None |
None |
Absence of a value |
Use type() to check a variable's type:
python
print(type(42)) # <class 'int'> print(type(3.14)) # <class 'float'> print(type("hello")) # <class 'str'> print(type(True)) # <class 'bool'>
Python Playground
Output
Click "Run" to execute your codeStrings
Strings are sequences of characters. You can use single or double quotes:
python
single = 'Hello' double = "Hello" multi = """This is a multi-line string"""
F-Strings (Formatted Strings)
F-strings let you embed expressions inside strings:
python
name = "Alice" age = 30 print(f"My name is {name} and I am {age} years old.") print(f"Next year I'll be {age + 1}.")
Type Conversion
Convert between types using built-in functions:
python
# String to number x = int("42") # 42 y = float("3.14") # 3.14 # Number to string s = str(42) # "42" # Check truthiness bool(0) # False bool(1) # True bool("") # False bool("hello") # True
Python Playground
Output
Click "Run" to execute your codeMultiple Assignment
Python lets you assign multiple variables at once:
python
x, y, z = 1, 2, 3 a = b = c = 0