Python numbers

Number inPythonIt can be of 3 types:int,floatwithcomplex.


For integersintclass. You can use value literals to define integers:

age = 8

You can also useint()Constructor:

age = int(8)

Check if the variable is of typeint,you can use ittype()Global functions:

type(age) == int #True

Floating point number

Floating point numbers (fractions) are typesfloat. You can use value literals to define integers:

fraction = 0.1

Or usefloat()Constructor:

fraction = float(0.1)

Check if the variable is of typefloat,you can use ittype()Global functions:

type(fraction) == float #True


The plural is the typecomplex.

You can use value literals to define them:

complexNumber = 2+3j

Or usecomplex()Constructor:

complexNumber = complex(2, 3)

Once you have a complex number, you can get the real and imaginary parts:

complexNumber.real #2.0
complexNumber.imag #3.0

Similarly, check if the variable is of typecomplex,you can use ittype()Global functions:

type(complexNumber) == complex #True

Arithmetic operations of numbers

You can use arithmetic operators to perform arithmetic operations on numbers:+,-,*,/(distribution),%(More than),**(Exponentiation) and//(Floor division):

1 + 1 #2
2 - 1 #1
2 * 2 #4
4 / 2 #2
4 % 3 #1
4 ** 2 #16
4 // 2 #2

You can use the compound assignment operator

  • +=
  • -=
  • *=
  • /=
  • %=
  • ..and many more

You can also quickly perform operations on variables:

age = 8
age += 1

Built-in function

There are 2 built-in functions to help numbers:

abs()Returns the absolute value of the number.

round()Given a number, round its value to the nearest integer:

round(0.12) #0

You can specify the second parameter to set the decimal point precision:

round(0.12, 1) #0.1

The Python standard library provides several other mathematical utility functions and constants:

  • ThismathThe package provides regular mathematical functions and constants
  • ThiscmathThe software package provides utilities to handle complex numbers.
  • ThisdecimalThe software package provides utilities for using decimal and floating-point numbers.
  • ThisfractionsThe package provides utilities to use rational numbers

We will discuss some of them separately later.

More python tutorials: