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.

Creating values of common types

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:

points =42
print(type(points))# <class 'int'>

You can also check if something matches a type with isinstance():

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().

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.

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.

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
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.

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).

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:

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.

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:

score =92
print(f"Your score is {score} points.")

You can also get the length of a string with len():

password ="open_sesame"
print(len(password))


Example 3: Lists for changing collections

Lists store multiple values, and you can edit them.

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:

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.

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.

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:

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.

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.

is_logged_in =False

if is_logged_in:
print("Welcome back!")
else:
print("Please log in.")

Booleans often come from comparisons:

x =10
print(x >5)# True


Example 8: None for “no value yet”

None represents the absence of a value.

result =None

if resultisNone:
print("No result yet.")

A common example is when a function can’t find something:

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.

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
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.

print(int("5"))# 5
print(float("5"))# 5.0
print(str(5))# "5"

But this fails:

# 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.

# 3 < "4" would raise TypeError

A common beginner bug is comparing numbers stored as strings:

age ="12"

if age >"9":
print("This comparison is misleading!")

Convert first:

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.

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:

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 like 3, 100, 7
  • float: decimals like 3.14, 0.5
  • str: text like "hello"
  • bool: True or False
  • list: ordered collection you can change
  • tuple: ordered collection you don’t change
  • dict: key-value pairs like a mini database row
  • set: collection with no duplicates
  • None: “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.