Skip to main content

Python Numbers

Python gives you three numeric types:

  • int
  • float
  • complex

Assigning a value to a variable is all it takes to create one of these.

The type() function will confirm the type of any Python object.

Example

Show the type of each of these numeric variables:

Prompt
Write a Python program that creates three variables: an integer, a float, and a complex number. Print the type of each variable.
Output: complete Python program

Int

An int (short for integer) is a whole number with no decimals. It can be positive or negative and can be as long as you like.

Example

Integers:

Prompt
Write a Python program that creates three integer variables of different sizes (small, large, negative) and prints the type of each.
Output: complete Python program

Float

A float, short for "floating point number", has one or more decimals and can be positive or negative.

Floats can also be written in scientific notation, where an "e" marks the power of 10.

Example

Floats:

Prompt
Write a Python program that creates three float variables and prints the type of each.
Output: complete Python program

Example

Floats written in scientific notation:

Prompt
Write a Python program that creates three float variables using scientific notation (e) and prints the type of each.
Output: complete Python program

Complex

A complex number uses a "j" to mark its imaginary part.

Example

Complex:

Prompt
Write a Python program that creates three complex number variables and prints the type of each.
Output: complete Python program

Type Conversion

The int(), float(), and complex() functions turn a number of one type into another type.

Note: A complex number can't be converted to any other number type.

Example

Converting between types:

Prompt
Write a Python program that converts between int, float, and complex types and prints the values and types of the converted variables.
Output: complete Python program

Random Number

Python has no random() function for producing a random number. What it does have is a built-in module named random, which does this job.

Example

Import the random module and show a random number between 1 and 9:

Prompt
Write a Python program that imports the random module and prints a random number between 1 and 9.
Output: complete Python program