/

Python Numbers: An Introduction to Integers, Floats, and Complex Numbers

Python Numbers: An Introduction to Integers, Floats, and Complex Numbers

In Python, numbers are classified into three types: int, float, and complex. This blog post will provide an overview of each type and demonstrate how to perform arithmetic operations on numbers.

Integer Numbers

Integer numbers are represented using the int class. You can define an integer by assigning a value to a variable:

1
age = 8

Alternatively, you can use the int() constructor to define an integer:

1
age = int(8)

To check if a variable is of type int, you can use the type() function:

1
type(age) == int  # True

Floating Point Numbers

Floating point numbers, also known as fractions, are of type float. You can define a floating point number using a value literal:

1
fraction = 0.1

Alternatively, you can use the float() constructor:

1
fraction = float(0.1)

To check if a variable is of type float, you can use the type() function:

1
type(fraction) == float  # True

Complex Numbers

Complex numbers are of type complex. You can define them using a value literal:

1
complexNumber = 2+3j

Alternatively, you can use the complex() constructor:

1
complexNumber = complex(2, 3)

Once you have a complex number, you can access its real and imaginary parts:

1
2
complexNumber.real  # 2.0
complexNumber.imag # 3.0

To check if a variable is of type complex, you can use the type() function:

1
type(complexNumber) == complex  # True

Arithmetic Operations on Numbers

Python provides various arithmetic operators for performing operations on numbers: + (addition), - (subtraction), * (multiplication), / (division), % (remainder), ** (exponentiation), and // (floor division). Here are a few examples:

1
2
3
4
5
6
7
1 + 1  # 2
2 - 1 # 1
2 * 2 # 4
4 / 2 # 2.0
4 % 3 # 1
4 ** 2 # 16
4 // 2 # 2

You can also use compound assignment operators like +=, -=, *=, /=, and so on, to quickly perform operations on variables:

1
2
age = 8
age += 1

Built-in Functions

Python provides two built-in functions that are useful for working with numbers:

  • abs() returns the absolute value of a number.
  • round() rounds a number to the nearest integer. You can specify a second parameter to round to a specific decimal point precision:
1
2
round(0.12)  # 0
round(0.12, 1) # 0.1

Additionally, the Python standard library provides several math utility functions and constants:

  • The math package offers general math functions and constants.
  • The cmath package provides utilities for working with complex numbers.
  • The decimal package provides utilities for working with decimals and floating point numbers.
  • The fractions package offers utilities for working with rational numbers.

In later discussions, we will explore some of these math utilities and constants in more detail.

Tags: Python, numbers, integers, floats, complex numbers, arithmetic operations, built-in functions