- __init__() function
- Aliases
- and operator
- argparse
- Arrays
- Booleans
- Break statement
- Bytes
- Classes
- Closure
- Code blocks
- Comments
- Conditional statements
- Console
- Context manager
- Data class
- Data structures
- Data types
- Data visualization
- datetime module
- Decorator
- Dictionaries
- Dictionary comprehension
- Django
- Docstrings
- Encapsulation
- enum
- enumerate() function
- Equality operator
- Error handling
- Exception handling
- False
- File handling
- Filter()
- Flask framework
- Floats
- Floor division
- For loops
- Formatted strings
- Functions
- Generator
- Globals()
- Greater than operator
- Greater than or equal to operator
- If statement
- in operator
- Indices
- Inequality operator
- Inheritance
- Integers
- Iterator
- Lambda function
- len() Function
- Less than operator
- Less than or equal to operator
- List append() method
- List comprehension
- List count()
- List insert() method
- List pop() method
- List reverse() method
- List sort() method
- Lists
- Logging
- map() function
- Match statement
- Math module
- Merge sort
- Min()
- Modules
- Modulo operator
- Multiline comment
- Multiprocessing
- Multithreading
- None
- not operator
- NumPy library
- OOP
- Optional arguments
- or operator
- Override method
- Pandas library
- Parameters
- pathlib module
- Pickle
- Polymorphism
- print() function
- Property()
- Protocol
- Random module
- range() function
- Raw strings
- Recursion
- Reduce()
- Regular expressions
- requests Library
- return statement
- round() function
- Script
- Set comprehension
- Sets
- SQLite
- String decode()
- String find()
- String join() method
- String replace() method
- String split() method
- String strip()
- Strings
- Ternary operator
- time.sleep() function
- True
- try...except statement
- Tuples
- Type casting
- Variables
- Virtual environment
- What is Python?
- While loops
- yield
- Zip function
PYTHON
Python Data Types: Syntax, Usage, and Examples
Python data types describe what kind of value you’re working with, like numbers, text, or collections. They affect what operations you can do, how data is stored, and how your code behaves.
How to Use Data Types in Python
You don’t usually “set” a type in Python. Python figures it out for you based on the value you assign, which is called dynamic typing.
Learn Python on Mimo
Creating values of common types
Python
age =29# int
temperature =18.5# float
is_online =True# bool
username ="milo"# str
scores = [10,8,9]# list
profile = {"role":"admin"}# dict
Python decides the type when you assign the value.
Checking a value’s type
Use type() to see what type a value has:
Python
points =42
print(type(points))# <class 'int'>
You can also check if something matches a type with isinstance():
Python
value ="42"
print(isinstance(value,str))# True
Converting between types
Python lets you convert values using built-in functions like int(), float(), str(), and list().
Python
price ="19.99"
price_number =float(price)
count ="7"
count_number =int(count)
message =str(123)
Conversions are helpful, but they can also throw errors if the value doesn’t make sense.
Python
text ="hello"
# int(text) would raise a ValueError
When to Use Data Types
Data types matter any time you store values, compare them, or pass them into functions. Here are some common situations where choosing the right one makes your life easier.
1) Representing different kinds of data
A user’s name is text, so you use a string. Their age is a number, so you use an integer. A list of favorite movies belongs in a list.
Python
name ="Amina"
age =26
favorite_movies = ["Interstellar","Spirited Away","Dune"]
2) Storing multiple items together
Collections help you group values that belong together.
- Use a list when order matters and the values can change
- Use a tuple when order matters and the values should stay fixed
- Use a dictionary when you want key-value pairs
Python
colors = ["red","green","blue"]# list
coordinates = (42.5,19.3)# tuple
user = {"name":"Leo","is_member":True}# dict
3) Validating inputs and avoiding bugs
A lot of bugs happen when your code expects one type but gets another.
Example: user input from input() always comes in as a string.
Python
age_input =input("Enter your age: ")
age =int(age_input)# convert to int before math
If you forget the conversion, adding numbers won’t work the way you expect.
Examples of Data Types in Python
Now let’s look at realistic examples of how types show up in everyday code.
Example 1: Numbers, math, and rounding
Python supports integers (int) and decimals (float).
Python
items =3
price_per_item =4.99
total = items * price_per_item
print(total)# 14.97
Floats can sometimes display small precision issues, so you might format output when showing money:
Python
total =14.97
print(f"Total: €{total:.2f}")
If you need exact decimal calculations for finance, many projects use the decimal module, but float is fine for most learning examples.
Example 2: Strings for text and formatting
Strings (str) store text.
Python
first_name ="Noah"
last_name ="Kim"
full_name = first_name +" " + last_name
print(full_name)
F-strings are often the cleanest way to format text:
Python
score =92
print(f"Your score is {score} points.")
You can also get the length of a string with len():
Python
password ="open_sesame"
print(len(password))
Example 3: Lists for changing collections
Lists store multiple values, and you can edit them.
Python
shopping_list = ["milk","eggs","rice"]
shopping_list.append("tea")
print(shopping_list)# ['milk', 'eggs', 'rice', 'tea']
Lists can also contain different types, but mixing types can make your code harder to reason about:
Python
mixed = [1,"two",True]
Example 4: Tuples for “don’t change this”
Tuples are like lists, but they are immutable, meaning you can’t change them after creation.
Python
location = (42.43,19.26)# latitude, longitude
Tuples are useful for things that come in fixed pairs or groups.
Example 5: Dictionaries for key-value data
Dictionaries (dict) are great when values need labels.
Python
book = {
"title":"The Hobbit",
"author":"J.R.R. Tolkien",
"pages":310
}
print(book["title"])
If a key might not exist, use .get() instead of indexing:
Python
rating = book.get("rating")
print(rating)# None
Example 6: Sets for “no duplicates allowed”
Sets store unique values only. If you add the same item twice, it still appears once.
Python
tags = {"python","backend","learning"}
tags.add("python")
print(tags)# still only one "python"
Sets are useful for filtering duplicates fast.
Example 7: Booleans for decisions
Booleans (True and False) control flow in your program.
Python
is_logged_in =False
if is_logged_in:
print("Welcome back!")
else:
print("Please log in.")
Booleans often come from comparisons:
Python
x =10
print(x >5)# True
Example 8: None for “no value yet”
None represents the absence of a value.
Python
result =None
if resultisNone:
print("No result yet.")
A common example is when a function can’t find something:
Python
deffind_user(users, username):
for userin users:
if user["username"] == username:
return user
returnNone
Learn More About Data Types
Once the basics feel comfortable, a few extra ideas will help you write cleaner code and avoid annoying errors.
Mutable vs immutable types
Some types can be changed after creation (mutable), and others can’t (immutable).
Mutable types:
- list
- dict
- set
Immutable types:
- int
- float
- bool
- str
- tuple
This matters when you pass values into functions.
Python
defadd_item(items):
items.append("new")
my_list = ["a","b"]
add_item(my_list)
print(my_list)# ['a', 'b', 'new']
The list changed because lists are mutable.
Truthy and falsy values
In Python, some values behave like False in conditions, even if they are not literally False.
Falsy values include:
0""(empty string)[](empty list){}(empty dict)None
Python
name =""
ifnot name:
print("Name is missing.")
This is convenient, but be careful, because 0 might be a valid value.
Type conversion gotchas
Some conversions fail, and some do surprising things.
Python
print(int("5"))# 5
print(float("5"))# 5.0
print(str(5))# "5"
But this fails:
Python
# int("5.7") would raise ValueError
If you expect decimals, convert to float() first.
Why types matter in comparisons
Python doesn’t let you compare unrelated types in most cases.
Python
# 3 < "4" would raise TypeError
A common beginner bug is comparing numbers stored as strings:
Python
age ="12"
if age >"9":
print("This comparison is misleading!")
Convert first:
Python
age =int(age)
if age >9:
print("Now it makes sense.")
Using types to design better functions
Clear types make functions easier to use, even in a dynamically typed language like Python.
Python
defaverage(numbers):
returnsum(numbers) /len(numbers)
scores = [8,9,10]
print(average(scores))
If someone passes a string by mistake, your function will crash. Simple checks help:
Python
defaverage(numbers):
ifnotisinstance(numbers,list):
returnNone
returnsum(numbers) /len(numbers)
A quick “cheat sheet” of common Python types
Here’s a quick mental map you can keep in your head:
int: whole numbers like3,100,7float: decimals like3.14,0.5str: text like"hello"bool:TrueorFalselist: ordered collection you can changetuple: ordered collection you don’t changedict: key-value pairs like a mini database rowset: collection with no duplicatesNone: “no value”
Summary
Data types in Python describe the kind of value you’re working with, which shapes what your code can do with it. Numbers, strings, booleans, lists, tuples, dictionaries, sets, and None cover most day-to-day programming needs. Once you understand how they behave, type conversion, mutability, and truthy or falsy values become much easier to handle without surprise bugs.
Join 35M+ people learning for free on Mimo
4.8 out of 5 across 1M+ reviews
Check us out on Apple AppStore, Google Play Store, and Trustpilot