Data Types in Python: A complete Tutorial

Welcome to one of the most exciting parts of your Python journey – understanding data types! Think of data types as the different "flavors" of data Python can work with. Just like we use different containers for water, snacks, or books in real life, Python uses different data types to store and manage different kinds of information. Whether you're storing a person's name, counting the number of steps in your fitness tracker, checking if the light is on or off, or collecting a list of favorite movies – Python needs to know what kind of data it is dealing with to use it properly. In this tutorial, we're going to explore Python’s core data types: integers, floats, strings, booleans, and NoneType. We'll also get a sneak peek at collections like lists, tuples, sets, and dictionaries. To make this fun and interactive, you’ll not only learn the definitions but also play with real-life examples, short quizzes, and hands-on exercises that will make these concepts click. By the end of this section, you'll be confidently identifying and using Python's basic data types like a pro!

Python Basic Data Types

In Python, data types define the kind of value a variable can hold. Since Python is a dynamically-typed language, you don’t need to explicitly declare the type of variable; it automatically detects the data type based on the value assigned. Python supports several built-in data types that fall into different categories such as numeric, text, boolean, sequence, and mapping types. These types help Python manage memory efficiently and allow you to perform operations suitable for the data. Understanding these basic data types is crucial for mastering Python as they form the foundation of data processing, control flow, and manipulation in any Python program.

Class Data Type Example
Text Type str "Hello, World"
Numeric int 10, -3, 0
float 3.14, -0.01
complex 3 + 5j
Sequence list [1, 2, 3]
tuple (1, 2, 3)
range range(5)
Mapping dict {"name": "Ankit"}
Set set {1, 2, 3}
frozenset frozenset([1, 2])
Boolean bool True, False
Binary bytes b'hello'
bytearray bytearray(5)
memoryview memoryview(b'abc')
None Type NoneType None

Integer Numbers

In Python, an integer represents a whole number — positive, negative, or zero — without a decimal point. They are one of the most commonly used data types, especially when counting, indexing, or looping. For example, if you are keeping track of a user's age or the number of items in a shopping cart, you would use integers.

>>> type(42)
<class 'int'>

In the following sections, you’ll learn the basics of how to create and work with integer numbers in Python.

Integer Literals

When you're writing programs, you often need to deal with whole numbers—like age, score, or quantity. In Python, you can represent these whole numbers directly in your code using integer literals.

An integer literal is a fixed value written directly into your code that represents an integer. It’s a basic way of saying: “this is a number, use it as-is.”

Common Forms of Integer Literals:

You can write integer values directly using digits, just like in mathematics:

>>> 50
50

>>> -12
-12

>>> 0
0

In the above examples:

  • 50 is a positive integer
  • -12 is a negative integer
  • 0 is zero, also an integer

To write negative integers, simply put a minus sign (-) before the number.

No Size Limit

One amazing thing about Python is that it doesn’t limit how big an integer can be. If your system has enough memory, Python can handle huge integers easily:

>>> 987654321987654321987654321987654321 + 1
987654321987654321987654321987654322

However, if you're trying to convert an extremely large integer into a string (like for printing), Python might raise an error after a certain size. You can adjust this behavior using a setting from the sys module.

Better Readability with Underscores

For large numbers, you can use underscores (_) to improve readability, like commas in regular writing:

>>> 1_000_000
1000000

Python ignores the underscores when processing the number, so 1_000_000 is the same as 1000000, but it’s easier on the eyes.

Integer Literals in Different Bases

Besides the regular base-10 (decimal) format, Python also supports other number systems to write integer literals:

Prefix Base Number System Example
0b or 0B 2 Binary 0b1010 (== 10)
0o or 0O 8 Octal 0o12 (== 10)
0x or 0X 16 Hexadecimal 0xA (== 10)

Examples:

>>> 0b11
3

>>> 0o11
9

>>> 0x11
17

Even though you write the values in different bases, Python internally treats them all as int type:

>>> type(0x11)
<class 'int'>

Integer Methods

In Python, integers (int) are objects, and they support a few useful methods. While not as many as lists or strings, these methods can help perform operations or conversions involving integer values.

Here are some essential methods that you can use with Python integers:

Method Description
.bit_length() Returns the number of bits required to represent the number in binary (excluding sign and leading zeros).
.bit_count() Returns the number of ones (1s) in the binary representation of the absolute value.
.to_bytes(length, byteorder) Returns a byte representation of the integer. You must specify the number of bytes and byte order.
int.from_bytes(bytes, byteorder) Converts a byte object back into an integer.
.as_integer_ratio() Returns a tuple of two integers whose ratio equals the original number.
.is_integer() Returns True if the number is an integer (applicable to float objects).

When you use the .as_integer_ratio() method on an integer, it returns the integer itself as the numerator and 1 as the denominator. While it works on integers, it's more useful when working with floating-point numbers.

Python's int type also has a method called .is_integer(). Although it always returns True for integers, it exists primarily for compatibility with float objects which also include this method.

Note: To use a method directly on an integer literal, wrap the number in parentheses:
(42).as_integer_ratio()  # Correct
42.as_integer_ratio()    # SyntaxError
This is necessary because the dot . also defines floating-point literals in Python.

The .bit_count() and .bit_length() methods are useful for digital signal processing tasks. For example, you might need to check if a binary signal has an even number of set bits (parity check):

signal = 0b11010110
set_bits = signal.bit_count()

if set_bits % 2 == 0:
    print("Even parity")
else:
    print("Odd parity")

In the example above, .bit_count() helps ensure the signal follows correct parity rules, providing a basic form of error detection.

The .to_bytes() and .from_bytes() methods are very helpful in network programming. When sending data over a network, you can convert an integer into bytes using .to_bytes(). Once received, .from_bytes() can be used to convert it back into an integer.

The Built-in int() Function in Python

The int() function in Python is a powerful built-in tool that allows you to convert different types of data into integers. It can take a float, a numeric string, or even a number in a different base (like binary or hexadecimal), and return its integer equivalent.

Syntax:

int(x=0, base=10)
  • x – The number or string you want to convert (optional).
  • base – The base of the input number (optional, default is 10).

Examples:

# Convert float to integer
print(int(10.5))       # Output: 10

# Convert string to integer
print(int("100"))      # Output: 100

# Convert binary to decimal
print(int("0b1010", 2)) # Output: 10

You can also use the int() function with different base values like 2 for binary, 8 for octal, and 16 for hexadecimal.

Tip: If you're converting strings from different bases, always specify the correct base using the second argument in int().

Floating-Point Numbers

In Python, numbers are one of the most important data types. And among them, floating-point numbers, or floats, are commonly used when you need to represent numbers with decimal points. Whether you're calculating measurements, prices, or scientific results — floats are what you need.

Let’s explore everything about floating-point numbers in Python: from literals to methods, and how they’re internally represented.

Floating-Point Literals in Python

Let’s start with the basics. A floating-point literal is just a number written with a decimal point or using scientific notation (exponential form). Python automatically recognizes it as a float.

x = 3.14
y = 0.0
z = -15.75
scientific = 1.5e2  # Equivalent to 1.5 × 10^2 = 150.0

Also, you can add underscores for readability in large numbers:

pi = 3.141_592_653_589
✅ Note: Underscores do not affect the value — they are just visual helpers.

How Are Floating-Point Numbers Represented in Python?

Internally, Python follows the IEEE 754 double-precision standard for storing floating-point numbers. This standard is widely used across most programming languages.

  • Floats are stored using 64 bits.
  • You get around 15–17 significant decimal digits of precision.
  • Some numbers cannot be stored exactly — which leads to common floating-point rounding errors.
print(0.1 + 0.2)  # Output: 0.30000000000000004
⚠️ Note: This is why floats should never be used for exact comparisons in conditions. Always use a small threshold instead.
abs((0.1 + 0.2) - 0.3) < 1e-9  # True

Floating-Point Methods in Python

Python also offers some helpful methods directly on floating-point numbers. Let’s explore the most useful ones:

🔸 .as_integer_ratio()

This method converts a float into a tuple of two integers – the numerator and the denominator. Useful when you want to understand the internal binary representation of the float as a fraction.

x = 0.75
print(x.as_integer_ratio())  # Output: (3, 4)
💡 Note: Works perfectly with exact fractions. Might return large integers for approximations.

🔸 .is_integer()

This method checks whether a float has a fractional part or not. Returns True if the float is mathematically an integer.

print(5.0.is_integer())    # True
print(5.1.is_integer())    # False

🔸 .hex() and .fromhex()

Python can convert floats to hexadecimal strings and back. Handy for debugging and working with low-level formats.

print(0.625.hex())  # '0x1.4p-1'
print(float.fromhex('0x1.4p-1'))  # 0.625

The Built-in float() Function in Python

The float() function is the most common way to convert other data types into a floating-point number.

float(5)        # 5.0
float("3.14")   # 3.14
float("2.5e2")  # 250.0
❌ Error: Cannot convert a non-numeric string to float. Avoid using float("hello").
✅ Note: Commonly used for converting input() to floats for calculations.
Example
price_input = input("Enter the product price: ")
price = float(price_input)
print("Total with tax:", price * 1.18)

Floating-point numbers are incredibly powerful and essential for almost every real-world Python program. From prices to measurements, and from statistics to scientific models — floats handle everything with decimals.

However, due to their binary nature, they aren’t always perfectly precise. So while using them, always remember:

  • Don’t compare floats directly for equality.
  • Use built-in methods to explore internal representations.
  • Convert types carefully using float().

Complex Numbers in Python

Python has built-in support for complex numbers, which are numbers with both a real part and an imaginary part. A complex number looks like this:

a + bj where:

  • a is the real part (a float or integer)
  • b is the imaginary part (a float or integer)
  • j is used to indicate the imaginary part (just like i in mathematics)
# Example of a complex number
z = 4 + 5j
print(z)  # Output: (4+5j)

These are very useful in mathematics, physics, and engineering fields, especially when dealing with wave functions, electrical signals, etc.

# Another example
z1 = 3 + 2j
z2 = 1 - 7j
sum_result = z1 + z2
print("Sum:", sum_result)  # Output: (4-5j)

Complex Number Literals

A complex number literal is any value in the form of a + bj or a - bj. Python will automatically understand it as a complex number.

You can create them directly in the code:

# Complex literals
x = 2 + 3j
y = -1 - 4j
print(type(x))  # Output: <class 'complex'>
⚠️ Note: Python uses j to represent the imaginary part (not i as in mathematics), because i is commonly used for iteration variables.

You can also perform operations like:

z1 = 3 + 4j
z2 = 1 + 2j
print(z1 + z2)  # Output: (4+6j)
print(z1 * z2)  # Output: (-5+10j)

Complex Number Methods

Python provides some useful methods and attributes to work with complex numbers:

  • z.real - Returns the real part
  • z.imag - Returns the imaginary part
  • z.conjugate() - Returns the complex conjugate
z = 5 + 6j

print("Real part:", z.real)          # Output: 5.0
print("Imaginary part:", z.imag)    # Output: 6.0
print("Conjugate:", z.conjugate())  # Output: (5-6j)

This is particularly helpful in mathematical computations involving complex numbers.


The Built-in complex() Function

Python also provides a built-in function complex() to create complex numbers.

# Syntax:
# complex(real, imaginary)

a = complex(3, 4)
b = complex(2)  # Equivalent to 2 + 0j
c = complex(imag=5)  # Equivalent to 0 + 5j

print(a)  # Output: (3+4j)
print(b)  # Output: (2+0j)
print(c)  # Output: 5j

This is helpful when you're dealing with dynamically calculated real or imaginary parts in variables.

real_part = float(input("Enter real part: "))
imag_part = float(input("Enter imaginary part: "))
z = complex(real_part, imag_part)
print("Complex Number:", z)
❌ Note: You cannot use this function to directly convert a string like "4+5j" unless the format is exactly correct.

Strings and Characters

In Python, a string is a sequence of characters enclosed within single quotes (') or double quotes ("). Strings are used to store text, such as names, messages, commands, or any textual data.

name = 'Ankit'
greeting = "Hello, world!"
print(name)
print(greeting)

Python treats both single and double quotes the same. You can even use triple quotes (''' or """) for multiline strings.

multiline = '''This is
a multiline
string'''
print(multiline)

Each string is an object of the str class and supports many useful methods for manipulation, analysis, and formatting.


Regular String Literals

Regular string literals are created using quotes. These strings can include letters, digits, symbols, and even whitespace characters.

text1 = 'Python'
text2 = "Learning is fun!"
print(text1 + " - " + text2)

Regular strings can span one line or use escape sequences (like \n, \t) to control formatting. These strings are mutable in terms of variable content, but the actual string value is immutable.


Escape Sequences in Strings

Escape sequences allow you to include special characters inside strings by prefixing them with a backslash (\).

  • \n - Newline
  • \t - Tab
  • \\ - Backslash
  • \' - Single quote
  • \" - Double quote
quote = "He said, \"Python is awesome!\""
path = "C:\\Users\\Ankit\\Documents"
print(quote)
print(path)

These escape characters help you avoid syntax issues and display output correctly.


Raw String Literals

A raw string tells Python to ignore escape sequences and treat backslashes as literal characters. You create it by prefixing the string with r or R.

path = r"C:\Users\Ankit\Documents\NewFolder"
print(path)  # Output: C:\Users\Ankit\Documents\NewFolder

Raw strings are especially useful for regular expressions, file paths, and any time you want to avoid accidental escape sequences.


F-String Literals (Formatted Strings)

F-strings (available from Python 3.6+) allow you to embed expressions directly inside string literals using curly braces {}. You prefix the string with f.

name = "Ankit"
age = 25
greeting = f"My name is {name} and I am {age} years old."
print(greeting)

F-strings are clean, readable, and support any Python expression inside the {} block.

print(f"5 + 3 = {5 + 3}")

They are faster and preferred over older formatting techniques like % or str.format().


String Methods

Python strings support a wide range of built-in methods to modify and analyze text.

  • .lower() – Converts to lowercase
  • .upper() – Converts to uppercase
  • .strip() – Removes leading/trailing whitespace
  • .replace() – Replaces a substring
  • .split() – Splits string by delimiter
  • .join() – Joins elements into a string
  • .find() – Finds index of substring
text = "  Hello, Python!  "
print(text.strip())          # "Hello, Python!"
print(text.lower())          # "  hello, python!  "
print(text.replace("Python", "World"))  # "  Hello, World!  "

Common Sequence Operations on Strings

Since strings are sequences, you can use operations like indexing, slicing, iteration, length, etc.

text = "Python"

# Indexing
print(text[0])     # P
print(text[-1])    # n

# Slicing
print(text[1:4])   # yth

# Length
print(len(text))   # 6

# Iteration
for char in text:
    print(char)

Strings are immutable, meaning you can’t change a character directly (you must create a new string).


The Built-in str() and repr() Functions

The str() function converts a value to a user-friendly string, while repr() gives a string that’s more for developers (often with quotes and escape characters).

num = 100
text = str(num)
debug = repr("Hello\nWorld")

print(text)   # 100
print(debug)  # 'Hello\nWorld'

Use str() when you want readable output (for end users), and repr() when you want accurate, debug-friendly output (for developers).


📦 Bytes and Byte Arrays in Python

In Python, bytes and bytearray are used for handling binary data. This is essential when working with files, networking, or low-level system operations.

  • bytes → immutable sequences of bytes (read-only)
  • bytearray → mutable sequences of bytes (you can modify it)

🔤 Bytes Literals

Bytes literals are defined using a b or B prefix followed by quotes. Only ASCII characters (0–127) are allowed.

b1 = b"Hello"
b2 = b'Python Bytes'

Each character is stored as its ASCII byte representation.

⚙️ The Built-in bytes() Function

The bytes() function creates a new bytes object. You can use it with integers, lists, or strings (with encoding).

# Create empty bytes
b = bytes()
print(b)  # Output: b''

# Create from integer
b = bytes(4)
print(b)  # Output: b'\x00\x00\x00\x00'

# Create from list of integers (0–255)
b = bytes([65, 66, 67])
print(b)  # Output: b'ABC'

🔧 The Built-in bytearray() Function

bytearray() is similar to bytes(), but it allows modification of content. Great for file and stream manipulation!

ba = bytearray([65, 66, 67])
print(ba)  # Output: bytearray(b'ABC')

# Modify
ba[0] = 68
print(ba)  # Output: bytearray(b'DBC')

🛠 Bytes and Bytearray Methods

  • hex() → returns hexadecimal string
  • decode() → converts bytes to string
  • startswith() → checks if it starts with certain bytes
  • find() → searches for a sub-byte pattern
b = b'Hello World'
print(b.hex())            # Output: 48656c6c6f20576f726c64
print(b.decode())         # Output: Hello World
print(b.startswith(b'He')) # Output: True
print(b.find(b'o'))       # Output: 4

✅ Booleans in Python

The Boolean type in Python can be either True or False. It is commonly used in conditional statements and logical operations.

x = True
y = False

print(type(x))  # Output: <class 'bool'>

Python evaluates many things as either True or False in conditionals:

  • False: 0, 0.0, '', [], {}, set(), None, False
  • True: Anything else (e.g., 1, "hello", [1], etc.)

🔢 Boolean Literals

There are only two boolean literals in Python:

  • True – equivalent to 1
  • False – equivalent to 0
print(True + True)   # Output: 2
print(False + True)  # Output: 1

🧪 The Built-in bool() Function

You can use the bool() function to convert any value to a Boolean. It follows Python's truthiness rules.

print(bool(10))        # True
print(bool(0))         # False
print(bool("Ankit"))   # True
print(bool(""))        # False
print(bool([]))        # False
print(bool([1, 2]))    # True

Conclusion

Mastering Python’s basic data types is a foundational step in your programming journey. From simple integers to complex strings and bytes, understanding these types allows you to write better, more effective, and more efficient Python code. Once you are comfortable with these data types, you'll find it easier to debug, build logic, and manipulate data in your projects.

Frequently Asked Questions - Python Data Types

1️⃣ What are the basic data types in Python?

Python supports the following basic data types:

  • int – Integer numbers (e.g., 10, -3)
  • float – Floating point numbers (e.g., 3.14, -0.5)
  • complex – Complex numbers (e.g., 4+5j)
  • str – Strings (e.g., "Hello")
  • bool – Boolean (True or False)
  • bytes and bytearray – Binary data
2️⃣ What is the difference between int and float?

int represents whole numbers (like 5, 0, -23) while float represents numbers with decimals (like 5.5, -0.3).

num1 = 5      # int
num2 = 5.5    # float
3️⃣ Are strings mutable in Python?

No, strings are immutable in Python. Once created, their contents cannot be changed. Any operation that modifies a string will return a new string.

4️⃣ What is the purpose of the complex data type?

The complex data type is used to handle complex numbers with real and imaginary parts. It’s useful in mathematics, engineering, and scientific computations.

z = 3 + 4j
5️⃣ What is the difference between str(), repr(), and format()?
  • str() returns a readable or user-friendly string.
  • repr() returns a detailed developer-friendly string (used for debugging).
  • format() or f-strings are used for embedding expressions and formatting values.
6️⃣ How can I check the type of a variable?

You can use the type() function to check the type of any object in Python:

x = 10
print(type(x))  # Output: <class 'int'>
7️⃣ What is the use of bool data type in Python?

The bool data type represents one of two values: True or False. It is commonly used in conditions, loops, and logical operations.

a = 5
b = 10
print(a < b)  # True
8️⃣ What is the difference between bytes and bytearray?
  • bytes are immutable sequences of bytes.
  • bytearray are mutable sequences of bytes (i.e., you can change individual elements).
b = bytes([65, 66, 67])
ba = bytearray([65, 66, 67])
9️⃣ Can I convert between data types in Python?

Yes! Python provides built-in type conversion functions like:

  • int()
  • float()
  • str()
  • bool()
  • complex()
x = "100"
print(int(x))  # Output: 100
🔟 Is Python dynamically typed?

Yes, Python is a dynamically typed language. This means you don’t need to declare a variable's type. It is automatically inferred at runtime.

x = 10       # int
x = "Ankit"  # now it's str
0 0 votes
Article Rating
Subscribe
Notify of
guest
0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x