Python online course

Python Numeric Variables: Integers, Floats, and Numeric Conversion

Learn how Python 3 stores numeric values in variables, uses integers and floats, converts between types, performs division, and handles floating-point precision.

In Python, a variable is a name that refers to a value or object. Numeric variables refer to numeric objects that can be used in calculations. This lesson targets Python 3 and focuses on integers, floating-point numbers, arithmetic, and type conversion.

For background, review what variables are and Python variable data types.

Python's Numeric Types

A numeric type is a built-in Python type used to represent numbers. The main built-in numeric categories are int, float, and complex.

TypeExample literalTypical useNotes
int42, -7, 0Whole-number counts and indexesPython 3 integers have arbitrary precision, subject to available memory
float3.14, 1.5e6Fractional values and measurementsUsually uses finite binary precision, so some decimals are approximate
complex2+3jValues with real and imaginary componentsComplex-number operations are outside the main scope of this lesson

Integer Variables

An integer is a whole number without a fractional component. Integer literals can be positive, negative, or zero.

positive = 25
negative = -8
zero = 0

print(positive)
print(negative)
print(zero)

Assignment gives a name to an integer object. The variable does not permanently have one type; it refers to whatever value is assigned to it at a particular time.

items = 12
print(items)
print(type(items))

The output includes 12 and <class 'int'>. The type() function reports the type of a value or expression.

Python 3 uses one integer type, int. It does not require a separate long type for larger integers. Python integers support arbitrary precision, meaning their size is not limited to a fixed 32-bit or 64-bit range. In practice, available memory and processing time limit how large an integer can become.

Floating-Point Variables

A floating-point number is a number represented by the float type that can include a fractional or decimal portion.

temperature = 21.5
price = 19.99

print(temperature)
print(type(temperature))

A decimal point normally makes a numeric literal a float, even when the fractional part is zero:

whole_float = 7.0
print(type(whole_float))  # <class 'float'>

Scientific notation is a compact way to write very large or very small floating-point values. The letter e means “times ten raised to.”

population = 1.25e6
small_value = 4.2e-3

print(population)   # 1250000.0
print(small_value)  # 0.0042

Floats are typically implemented with finite binary precision. Binary floating-point cannot represent every decimal fraction exactly. As a result, a calculation can display a small approximation error:

result = 0.1 + 0.2
print(result)  # 0.30000000000000004

This does not mean that Python's arithmetic is randomly incorrect. It reflects how the selected floating-point representation stores the values. For exact base-10 financial calculations, the decimal module is a related advanced topic.

Inspecting Numeric Types

Use type() to distinguish integers, floats, and complex values.

count = 5
ratio = 5.0
number = 2 + 3j

print(type(count))   # <class 'int'>
print(type(ratio))   # <class 'float'>
print(type(number))  # <class 'complex'>

The type of an expression's result can differ from the types of its operands. For example, dividing two integers with / produces a float in Python 3.

left = 5
right = 2
result = left / right

print(result)       # 2.5
print(type(result)) # <class 'float'>

Converting Numeric Values

Type conversion means changing a value from one type to another. The float() and int() functions perform common numeric conversions.

Converting an Integer to a Float

Use float(value) to convert an integer to a floating-point value.

number = 5
converted = float(number)

print(converted)       # 5.0
print(type(converted)) # <class 'float'>

The numeric value is represented as a float, so the displayed form commonly includes .0.

Converting a Float to an Integer

Use int(value) to convert a float to an integer. This operation performs truncation: it discards the fractional portion and moves toward zero. It does not round to the nearest whole number.

positive = int(5.9)
negative = int(-5.9)

print(positive)  # 5
print(negative)  # -5

If rounding is intended, use an appropriate rounding operation such as round() instead of assuming that int() rounds.

Numeric strings can also be converted when their contents have a valid format:

count = int('42')
measurement = float('3.14')

print(count)        # 42
print(measurement)  # 3.14
ExpressionInput typeResultImportant behavior
float(5)int5.0Creates a float representation
int(5.9)float5Truncates toward zero
int(-5.9)float-5Truncates toward zero, rather than flooring to -6
int('42')str42Requires a valid integer string
float('3.14')str3.14Requires a valid floating-point string

Invalid input causes a conversion error, commonly ValueError:

value = int('not a number')  # ValueError

When converting user input, validate the input or handle the exception. See getting user input and catching specific exceptions.

Arithmetic with Integers and Floats

Python supports addition with +, subtraction with -, multiplication with *, and division with /. For a broader operator reference, see Python arithmetic operators.

a = 10
b = 3

print(a + b)  # 13
print(a - b)  # 7
print(a * b)  # 30
print(a / b)  # 3.3333333333333335

True Division

True division uses /. In Python 3, it returns a float, including when both operands are integers.

print(6 / 2)       # 3.0
print(type(6 / 2)) # <class 'float'>

Floor Division

Floor division uses //. It returns the quotient rounded downward toward negative infinity. This is different from int(a / b), which truncates toward zero.

print(5 // 2)    # 2
print(-5 // 2)   # -3
print(int(-5 / 2))  # -2

Remainders

The remainder operator, %, gives the value left after division.

print(5 % 2)  # 1
print(8 % 2)  # 0

A remainder of zero is useful for testing whether an integer divides evenly. The % operator is also commonly used for repeating patterns and checking odd or even numbers.

OperatorExample using 5 and 2ResultResult typeMeaning
/5 / 22.5floatTrue division
//5 // 22intFloor division
%5 % 21intRemainder after division

Mixing Integers and Floats

Basic arithmetic involving a float generally produces a float. This behavior is often called type promotion.

total = 4 + 2.5
product = 3 * 1.5
quotient = 9 / 3

print(total, type(total))       # 6.5, float
print(product, type(product))   # 4.5, float
print(quotient, type(quotient)) # 3.0, float

Complex Numbers

A complex number has a real component and an imaginary component. Python writes the imaginary component with a j suffix.

value = 2 + 3j
print(value)       # (2+3j)
print(type(value)) # <class 'complex'>

Complex-number operations are outside the main scope of this lesson. They are useful in specialized mathematics, engineering, and signal-processing applications.

Python 3 Version Context

All examples in this lesson target Python 3. In Python 2, large integers could appear as a separate long type, while Python 3 uses int for integers of all supported sizes. Python 2 also commonly used integer division behavior for / when both operands were integers. In Python 3, / is true division and returns a float; use // when floor division is wanted. Python 3 is the recommended environment for these examples.

Troubleshooting Numeric Code

int() Produces a Value Smaller in Magnitude

If int(5.9) produces 5 or int(-5.9) produces -5, the code is truncating toward zero. Use round() when the goal is rounding rather than discarding the fractional part.

Integer Division Produces a Decimal

In Python 3, 5 / 2 produces 2.5 because / performs true division. Use 5 // 2 for floor division, and remember that negative values make floor division differ from truncation.

A Decimal Calculation Has an Unexpected Trailing Digit

Results such as 0.30000000000000004 occur because many decimal fractions have no exact finite binary representation. Treat ordinary floats as approximations when exact decimal representation matters.

int() or float() Raises ValueError

The input is not in a valid format for the requested conversion. For example, int('42') is valid, but int('forty-two') is not. Validate external input and handle conversion errors where necessary.

An Integer Seems to Have a Fixed Maximum

Python 3 int values are not restricted to a universal fixed-width range such as 64 bits. They grow as needed until available memory or practical computation limits are reached.

Practice Checklist

  • Assign positive, negative, and zero integer literals to variables.
  • Assign decimal literals and scientific-notation literals to float variables.
  • Use type() to inspect values and expression results.
  • Convert integers with float() and floats with int().
  • Remember that int() truncates toward zero rather than rounding.
  • Choose /, //, or % based on the required division result.
  • Expect ordinary floating-point arithmetic to have finite precision.