Python Numbers

3 min read ·

Python supports numeric data types to store numbers and perform mathematical operations. These numeric types are simple to use and automatically assigned when you give a value to a variable.
There are three numeric types in Python:
  • int
  • float
  • complex
Variables of numeric types are created when you assign a value to them.

Integer (int)

The int type is used to store whole numbers, positive or negative, without decimals.

Float (float)

The float type is used to store numbers with decimal points.

Complex Numbers (complex)

Complex numbers are written with a real part and an imaginary part. The imaginary part is written using j.

Access Real and Imaginary Parts


Type Conversion (Casting Numbers)

Python allows converting one numeric type into another using casting functions.

Convert to Integer


Convert to Float


Convert to Complex

Important
  • You cannot convert a complex number into int or float

Random Number

Python has a built-in module called random to generate random numbers.
To use it, you must import the module first.

Generate a Random Integer


Generate a Random Float


Choose a Random Value from a List


Check Numeric Type

You can use type() to check the numeric data type.

Exercise

  • Create one variable of each numeric type
  • Convert an integer to float and complex
  • Generate a random number between 1 and 100
  • Print the real and imaginary part of a complex number