Table of Contents

What Will You Learn
This tutorial provides a comprehensive overview of Python's numeric data types, offering practical examples and insights to enhance your programming skills.


Numeric data types are the foundation of computation and logic in any programming language. Without understanding them, it's impossible to correctly implement a loop, condition, or arithmetic operation. In the programming language, the variable type is not explicitly specified, but behind the scenes, each object has its own class, behavior, and limitations.

Working with numbers initially seems simple: assign a variable x = 10 — and everything works. But as the complexity of the project grows, the lack of knowledge about the differences between int, float, and complex becomes a problem: issues with division arise, unexpected rounding, and type errors in mathematical functions.

Therefore, studying numeric types should not begin with “what types exist,” but with understanding why they are needed, how they differ, and how they work in memory. This is not just terminology — it's the foundation upon which all computational logic of your program is built.

What are the numeric data types in Python?

The language has three built-in numeric types: int, float, and complex. Each is designed to store numbers but differs in precision, storage method, and allowed operations. The data type is assigned automatically — the interpreter itself determines what exactly you entered: an integer, a floating-point, or a complex number.

You can freely perform arithmetic between numbers of the same or different types. But the result of such operations will depend on the participating types. For example, dividing two int values returns a float. And the sum of a float and an int always results in a float.

Table: Main Numeric Types

php-template Копіювати Редагувати
Data Type Purpose Example
int Whole numbers, positive and negative x = 42
float Floating-point numbers (decimals) pi = 3.14159
complex Complex numbers, with real and imaginary parts z = 2 + 3j

Below we will look at each type in detail: how it is created, how it behaves in arithmetic, where it is used, and what pitfalls and conversions exist.

Python Integer

The int type is used to store whole numbers — both positive and negative, including zero. It is one of the most frequently used data types. The size of an integer is not limited by a fixed length as in some other languages: it automatically scales as needed, allowing you to work with very large values.

int supports all standard arithmetic operations: addition, subtraction, multiplication, division, integer division (//), modulo (%), exponentiation (**).

Example:

 
    a = 42 
    b = -7 
    c = 5 + 10 
    d = a // 4# Integer division 

Key Features:

  • Automatically determined when assigning an integer value;
  • No limit on the number size;
  • Participates in all arithmetic operations;
  • When dividing int / int, always returns float.

Python Float

The float type is intended for storing decimal numbers with a decimal point. These are floating-point numbers such as 3.14, -0.5, 2.0. It is used when precision is required in calculations, for example, in finance, statistics, or measurements.

By default, even division of two int values returns a float. Also, all numbers with a decimal point are automatically interpreted as float.

Example:

 
    pi = 3.14159 
    weight = float(70) 
    result = 5 / 2  # Returns 2.5

Key Features:

  • All numbers with a decimal point or in exponential form (1e6) are float;
  • May lose precision when working with very large or very small values;
  • Supports mathematical operations and functions (math.sqrt(), round(), etc.);
  • When used with int, the result is always float.

Python Complex

The complex type is used less often, but it is built into the language. It is used to represent complex numbers, which consist of a real and an imaginary part. The format is a + bj, where a is the real part and b is the imaginary part. The symbol j is standard for the imaginary unit in engineering and scientific mathematics.

Complex numbers are used in physics, electrodynamics, signal processing, and scientific computing. All operations — addition, multiplication, division, exponential functions — are available out of the box.

Example:

 
    z1 = 2 + 3j 
    z2 = complex(1, -4) 
    result = z1 + z2 # (3 - 1j)

Key Features:

  • Part of the standard library, available without import;
  • Uses the j suffix to indicate the imaginary part;
  • Supports arithmetic with complex numbers;
  • Not used in basic tasks, but essential in scientific fields.

Type Conversion in Python

Type conversion is the process by which a value of one data type is transformed into a value of another type. In the context of numbers, this means switching between int, float, complex, or converting a number to a string and vice versa.

Conversions in the language can be implicit (they happen automatically during operations between different types) or explicit (when the programmer manually applies type conversion functions: int(), float(), complex()).

Implicit Conversion

The interpreter automatically converts int to float if both types are involved in an expression:

 
    a = 5 # int 
    b = 2.0 # float 
    c = a + b # float → c = 7.0

The result here is float because float has higher precision, and data loss is unacceptable.

Explicit Conversion

The developer controls the type of value using built-in functions:

 
    x = int(4.9) # 4 — fractional part is discarded 
    y = float(3) # 3.0 
    z = complex(2, 5) # (2+5j)

Such conversions are useful when you need to guarantee a specific data type, for example, when working with user input (input() always returns a string).

Common Conversion Functions:

css Копіювати Редагувати
Function Purpose Example
int() Converts to an integer int(3.7)3
float() Converts to a floating-point number float("2")2.0
complex() Creates a complex number complex(3, 4)3+4j
str() Converts a number to a string str(10)"10"

It's important to understand that int("5.0") will cause an error — the string "5.0" must first be converted to float and then to int.

Beginner Mistakes

The transition from theory to practice is often accompanied by common mistakes. Below are the most frequent issues when working with numeric types and explanations on how to avoid them.

1. Attempting to Use a String as a Number

 
    x = input("Enter a number: ") 
    print(x + 5) # ❌ TypeError

Error: input() returns a string, and 5 is a number. You can't add different types without conversion.

✅ Solution:

 
    x = int(input("Enter a number: ")) 
    print(x + 5)

2. Loss of Precision When Converting float → int

 
    x = int(5.999) 
    print(x) # 5

Error: beginners often expect rounding instead of truncation.

✅ Solution: Use round() for rounding:

 x = round(5.999) # 6

3. Division Without Type Safety

 
    a = int(input()) 
    b = int(input()) 
    print("Result:", a / b)

Error: if b = 0, it will cause a ZeroDivisionError.

✅ Solution: Add a check:

 
    if b != 0: 
      print(a / b) 
    else: 
      print("Division by zero is not allowed.")

4. Improperly Formatted String Conversion

 x = int("3.14") # ❌ ValueError

Error: you cannot directly convert a string with a decimal point to int.

✅ Solution:

 x = float("3.14") 

If you need an int, additionally:

 x = int(float("3.14")) # → 3 

5. Misunderstanding the Result Type of Operations

 
    x = 3 
    y = 2 
    print(x / y) # → 1.5 (not 1)

Error: expecting an integer when dividing two int values.

✅ Explanation: The / operator always returns a float. Use // for an integer result:

 print(x // y) # → 1

These errors can be avoided by understanding the data type of each variable and what the result of each operation will be. This is especially important in a dynamically typed language, where everything is determined at runtime.

FAQ

In Python, which numeric type is used to represent real numbers?

To represent real numbers, Python uses the float data type. These are numbers with a decimal point, such as 3.14, -0.5, 2.0. The float type corresponds to 64-bit double-precision floating-point numbers, providing sufficient accuracy for most practical applications.

float is used in measurements, financial calculations, percentages, and mathematics where the fractional part matters. When performing operations between int and float, the result will always be a float — this ensures precision is maintained.

Which Python function can you use to convert a numeric data type into a string?

To convert a numeric value to a string, use the built-in str() function. It accepts a number of any type (int, float, complex) and returns its string representation:

 
    num = 42 
    text = str(num) # "42"

This is especially important when generating text messages or combining numbers with strings in print() or f-strings. Without converting to a string, an attempt to execute "Result: " + 42 will result in a TypeError. Using str() makes the code safe and readable.

How to safely convert a float string into an integer?

Directly passing a string with a decimal point to int() will raise an error:

 x = int("3.14") # ❌ ValueError

To convert such a string properly, first convert it to float, then to int:

 x = int(float("3.14")) # ✅ 3

This is a standard approach when handling user input, API data, or configuration files. Note that the fractional part will be truncated, not rounded. If you need mathematical rounding — use round().

How to check the numeric type of a variable in Python?

To determine the type of a variable, use the type() function:

 
    x = 5.0 
    print(type(x)) # 

If you need to check whether a variable belongs to a specific numeric type, use isinstance():

 isinstance(x, float) # True

This is a safe method, especially useful for conditions and data validation. isinstance() also supports checking against multiple types at once:

 isinstance(x, (int, float)) # True if x is int or float

How to round a float number to an integer in Python?

To round a float to the nearest whole number, use the round() function:

 
    x = round(3.7) # 4 
    y = round(2.3) # 2

round() returns an int and rounds according to standard mathematical rules: 0.5 and above rounds up, below 0.5 rounds down. This is different from int(), which simply truncates the decimal part:

 int(3.9) # 3

If you need to round a number to a certain number of decimal places (e.g., 2.456782.46), pass a second argument:

 round(2.45678, 2) # 2.46