Data types define the kind of value a variable holds. Python has several built-in types:
| Type | Example | Description |
|---|---|---|
int | x = 5 | Whole number |
float | pi = 3.14 | Decimal number |
str | name = "Alice" | Text string |
bool | is_ready = True | True or False |
list | [1, 2, 3] | Ordered collection |
tuple | (1, 2) | Immutable ordered collection |
dict | {"id": 1} | Key-value mapping |
set | {'apple', 'banana'} | Unique unordered values |
Use type() to find out the data type of a variable:
print(type("hello")) # <class 'str'>
print(type(3.14)) # <class 'float'>You can convert values from one type to another using built-in functions:
| Function | Converts To | Example |
|---|---|---|
int() | Integer | int("5") → 5 |
float() | Float | float("3.14") → 3.14 |
str() | String | str(42) → "42" |
bool() | Boolean | bool(0) → False |
x = "100"
y = int(x) # 100
z = float(x) # 100.0
score = 85
text = str(score) # "85"Note: Invalid strings cannot be converted to numbers, e.g., int("five") will throw an error.
Python is dynamically typed, which means you don’t need to declare a variable’s type and it can change at runtime:
x = 10 # int
x = "ten" # now a strThis adds flexibility but can lead to errors if you're not careful with operations between types:
x = "5"
print(x + 1) # ❌ TypeError: can't concatenate str and intname = "Alice"
age = 21
gpa = 3.82
is_graduated = False
grades = [90, 85, 95]
coordinates = (41.40338, 2.17403)
student = {"id": 1001, "name": "Bob", "enrolled": True}
tags = {"python", "react", "flask"}These types are commonly used in real applications — like storing user data, location, scores, and tags.
What will this print?
Hint: What is the type of x after the last assignment?
Ask the AI if you need help understanding or want to dive deeper in any topic