VMware ESXi and vSphere Cluster Management

Numeric Variables in Python

Learn how Python stores, identifies, converts, and calculates with int, float, and complex numeric variables.

A variable is a name that references a value. A numeric variable is a variable whose current value is a number. Numeric variables are useful for counting items, storing measurements, performing calculations, and controlling program logic.

This lesson uses Python 3. You should be familiar with basic assignment, print(), and the idea that values have data types.

Assigning Numeric Values to Variables

Use the equals sign (=) to assign a value to a variable. The name goes on the left, and the value or expression goes on the right.

items = 5
 temperature = 21.5
 total = items * 3

print(items)
print(temperature)
print(total)

In this example, items references an integer, temperature references a floating-point value, and total references the result of an arithmetic expression. Python determines the numeric type from the literal or expression assigned; you do not need to declare the type separately.

A numeric literal is a number written directly in source code. Examples include 5, -12, 0, and 3.5.

Integer Values

An integer is a whole-number value with no fractional component. Integers can be positive, negative, or zero. Python's built-in integer type is called int.

positive_count = 5
negative_temperature = -20
empty_count = 0

print(positive_count)
print(negative_temperature)
print(empty_count)
print(type(positive_count))

The last line displays <class 'int'>. Python 3 has one built-in integer type, int. In normal use, Python integers support arbitrary precision: they are not restricted to a fixed signed 64-bit range. Very large integers still require available memory and processing time, so “arbitrary precision” does not mean unlimited resources.

Common Uses for Integers

  • Counting products, attempts, or records
  • Representing indexes and whole-number quantities
  • Storing years or other discrete values
  • Controlling repetition and program decisions

Floating-Point Values

A floating-point number can represent a fractional value. In Python, the common built-in type for decimal-based calculations is float. A decimal point or exponential notation usually makes a numeric literal a float.

price = 5.3
measurement = -0.75
large_value = 1.2e3

print(price)
print(type(price))

price references a value of type float. The expression 1.2e3 uses exponential notation and means 1.2 multiplied by 10 to the third power, or 1200.0.

Floats use a finite binary representation. Many familiar decimal fractions cannot be represented exactly in binary, so calculations can contain tiny precision differences. This is normal behavior, not a broken arithmetic operator.

result = 0.1 + 0.2
print(result)

The displayed result may contain a small trailing difference from exactly 0.3. For ordinary measurements and many scientific calculations, this approximation is practical. For exact base-10 financial calculations, investigate Python's decimal module instead. Floats also have practical limits: values that are too large can overflow, and available memory and computation remain finite.

Common Python Numeric Types

Type       Example literal   Typical use                         Notes
int        42                Whole-number counts and indexes     Arbitrary-precision integers
float      3.14              Measurements and decimal arithmetic Approximate binary representation
complex    2 + 3j            Real and imaginary components       Uses j for the imaginary part

Inspecting Numeric Types

Use type(value) to inspect the type of a value or the value currently referenced by a variable.

value = 5
print(value, type(value))       # 5 <class 'int'>

value = 5.0
print(value, type(value))       # 5.0 <class 'float'>

A variable name does not permanently have one type. Reassignment makes the name reference a new value, so its associated type can change. In the example, value first references an int and then a float.

Converting Numeric Values

Type conversion means creating a value of one type from a value of another type. The main numeric conversion functions are int(), float(), and complex().

Converting to a Float

Use float(value) to convert an integer or compatible numeric text to a floating-point value.

whole_number = 5
as_float = float(whole_number)
text_number = float("3.14")

print(as_float)       # 5.0
print(text_number)    # 3.14

Converting to an Integer

Use int(value) to convert a float or compatible numeric text to an integer. When converting a float, int() removes the fractional component by truncating toward zero. It does not round to the nearest integer.

print(int(5.9))       # 5
print(int(-5.9))      # -5
print(int("42"))      # 42

For comparison, floor division rounds down toward negative infinity, while int() truncates toward zero. If you need rounding, use round() and choose its behavior deliberately.

Conversion Results

Expression       Result   Result type   Key behavior
float(5)         5.0      float         Adds a floating-point representation
int(5.9)         5        int           Truncates toward zero
int(-5.9)        -5       int           Truncates toward zero
int("42")        42       int           Parses valid integer text
float("3.14")    3.14     float         Parses valid decimal text

Conversion requires a valid representation. For example, int("five") and float("3,14") raise ValueError in basic Python parsing. Use a decimal point rather than a locale-style comma for simple float input, and validate or handle errors when values come from users.

Arithmetic with Numeric Variables

Python provides these common arithmetic operators:

  • + for addition
  • - for subtraction
  • * for multiplication
  • / for true division
  • // for floor division
  • % for the remainder
apples = 5
boxes = 2

print(apples + boxes)  # 7
print(apples - boxes)  # 3
print(apples * boxes)  # 10
print(apples / boxes)  # 2.5

True Division, Floor Division, and Remainders

In Python 3, / performs true division. It returns a float, even when both operands are integers.

quotient = 5 / 2
print(quotient)        # 2.5
print(type(quotient))  # <class 'float'>

Use // for floor division. It returns the result rounded down toward negative infinity, not merely the result with its fraction removed. Use % to calculate the remainder.

print(5 / 2)    # 2.5
print(5 // 2)   # 2
print(5 % 2)    # 1

print(-5 // 2)  # -3: down toward negative infinity
Expression   Result   Result type   Meaning
5 / 2        2.5      float         True division
5 // 2       2        int           Floor division
5 % 2        1        int           Remainder

Combining Integers and Floats

When an integer and a float participate in ordinary arithmetic, the result is generally a float.

count = 5
rate = 0.5
result = count + rate

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

Complex Numbers

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

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

complex is another built-in Python numeric type. This introductory example is enough to recognize complex literals; detailed complex arithmetic is a separate topic.

Python 3 Division Behavior

All examples in this lesson target Python 3. In Python 3, 5 / 2 produces 2.5, and 5 // 2 performs floor division. Historically, Python 2 separated int and long for integer sizes and handled division between integers differently. Do not apply those historical rules to Python 3 code.

Troubleshooting Numeric Code

Expecting Integer Division

If 5 / 2 produces 2.5 instead of 2, remember that / is true division in Python 3. Use // when floor division is intended, especially after considering how negative operands should behave.

Expecting int() to Round

int(5.9) returns 5, and int(-5.9) returns -5, because conversion truncates toward zero. Use round() when rounding is required.

Conversion Raises ValueError

Expressions such as int("five") or float("3,14") fail because the text is not a valid representation for that conversion. Clean or validate input and handle ValueError when processing user-provided text.

A Decimal Result Has an Unexpected Tail

A result such as 0.1 + 0.2 may not display exactly as 0.3. This occurs because finite binary floating-point cannot exactly represent many decimal fractions. Use appropriate tolerance-based comparisons for floats, or use decimal when exact decimal arithmetic is required.

A NameError Appears

A NameError during arithmetic usually means the variable name has not been assigned yet, or its spelling does not match. Assign a numeric value before using the name and check the spelling consistently.

Key Points

  • A variable is a name that references a value; a numeric variable currently references a number.
  • int represents whole numbers, including positive values, negative values, and zero.
  • float represents approximate decimal-capable values.
  • complex represents values with real and imaginary parts and uses j for the imaginary component.
  • Use type() to inspect a value's current type.
  • float() and int() convert compatible values, but int() truncates toward zero.
  • In Python 3, / returns a float, // performs floor division, and % returns a remainder.
  • Mixing an int and a float generally produces a float.
  • Floating-point values are approximate because they use finite binary representation.