Python : Numbers

In Python, numbers are represented using various numeric data types. The main numeric data types in Python include integers, floating-point numbers, and complex numbers. Here's a brief overview of each type:

1. Integers (`int`): Integers represent whole numbers without any fractional or decimal part. They can be positive or negative.

 
   x = 5
   y = -10

 

2. Floating-Point Numbers (`float`): Floating-point numbers represent real numbers with a fractional part. They are written with a decimal point.

 
   pi = 3.14159
   temperature = -20.5

  

3. Complex Numbers (`complex`): Complex numbers consist of a real part and an imaginary part, written in the form `a + bi`, where `a` is the real part, `b` is the imaginary part, and `i` is the imaginary unit.

   
   z = 3 + 4j
 

Python also provides built-in functions and operators for working with numbers, including arithmetic operations (`+`, `-`, `*`, `/`, `//` for integer division, `%` for modulus), comparison operators (`==`, `!=`, `<`, `>`, `<=`, `>=`), and mathematical functions (e.g., `abs()`, `pow()`, `round()`).

Here are some examples of using these operations:


# Arithmetic operations
result = 10 + 5       # Addition
result = 10 - 5       # Subtraction
result = 10 * 5       # Multiplication
result = 10 / 5       # Division
result = 10 // 3      # Integer division
result = 10 % 3       # Modulus
result = 2 ** 3       # Exponentiation

# Comparison operations
is_equal = (10 == 5)      # Equal to
is_not_equal = (10 != 5)  # Not equal to
is_greater = (10 > 5)     # Greater than
is_less = (10 < 5)        # Less than
is_greater_equal = (10 >= 5)  # Greater than or equal to
is_less_equal = (10 <= 5)     # Less than or equal to

# Mathematical functions
absolute_value = abs(-10)      # Absolute value
power = pow(2, 3)              # Exponentiation
rounded_value = round(3.14159) # Rounding

 

Python also supports working with numeric literals in different bases, such as binary (`0b`), octal (`0o`), and hexadecimal (`0x`). For example:


binary_number = 0b1010     # Binary literal (decimal value: 10)
octal_number = 0o12        # Octal literal (decimal value: 10)
hexadecimal_number = 0xA   # Hexadecimal literal (decimal value: 10)

 

These are some of the basics of working with numbers in Python. Python's flexible numeric system allows you to perform a wide range of numerical computations and operations.