Numeric Data Types in Python

Python provides several built-in data types to represent numerical values:

  • Integers: Representing whole numbers without any fraction. Integers can be constructed using int().
  • Floating-point numbers: Numbers with fractional parts. Floats can be constructed using float().
  • Boolean: Representing logical results, which can take either True or False. Booleans can be constructed using bool().

In Python, all numeric data types are immutable, meaning that once created, you cannot alter their values. If you attempt to modify an immutable object, Python creates a new object with the new value instead. For example:

x = 42 # Assigning an integer value
y = x # Creating a new reference to the same integer literal

x = 10 # Trying to Modify the value of x

print(x) # Output: 10
## 10
print(y) # Output: 42
## 42


In this example, x is initially assigned the value 42, and y is created as a new reference to the same integer. Later, an attempt is made to modify the value of x by reassigning it to 10. However, due to the immutability of integers in Python, this attempt creates a new integer object with the value 10, while y still references the original value 42. Therefore, x references 10, and y references 42.



Operations on Integers and Floats

In programming, an operator is a symbol or keyword that executes an operation on two operands. These operators are fundamental elements of programming languages, enabling the manipulation of data, execution of calculations, and facilitation of decision-making processes. The applicability of operators and outcomes they yield depend on the data types involved. Thus, it is important to be aware the data type on which an operator is applied and the resulting data type.

Below is a list of operators that can be applied to Python integers and floats.

  1. Arithmetic Operators: Perform mathematical operations like addition, subtraction, multiplication, and division. Output will be either integer or floating numbers.
    • +: Addition
    • -: Subtraction
    • *: Multiplication
    • /: Division
    • %: Modulo
    • **: Exponentiation
    • //: Floor Division
  2. Comparison Operators: Compare two values and return a Boolean result (True or False) based on the comparison.
    • ==: Equal to
    • !=: Not equal to
    • <: Less than
    • >: Greater than
    • <=: Less than or equal to
    • >=: Greater than or equal to


Arithmetic Operations on Integers and Floats

The following code lines provide examples demonstrating the behavior of the arithmetic operations when applied to two integers. Note that executing division between the two integers yields a floating-point number. Python always outputs a float from division, even when the output is a whole number. This behavior is called type coercion or type promotion.

4 + 2 # Add 2 to 4
## 6
4 - 2 # Subtract 2 from 4
## 2
4 * 2 # Multiply 4 by 2
## 8
4 / 2 # Divide 4 by 2
## 2.0
4 ** 2 # 4 to the 2nd power
## 16


In programming, type coercion refers to the automatic conversion of one data type to another, typically to facilitate operations between two different types. In the example above, Python promoted the results of division between the two integers to a float, in order to maintain precision and avoid loss of information.

Similarly, applying an arithmetic operator to an integer and a float will promote the result to a float in order to accommodate the more precise data type. For example:

type(1 + 2.0)
## <class 'float'>


To convert a float to an integer, you should use the integer constructor, int(). It is important to note that int() does not round the number, but truncate it. For example:

int(9.999999)
## 9


To round a number to the nearest integer (or any other desired decimal place), you can use the round() function.

round(1/3, 1) # round(number, ndigits=None)
## 0.3


One of the pitfalls of using floating-point numbers in programming is that they are evaluated as approximations, not exact values! For example, let’s consider the expression below.

1.2 - 1.0
## 0.19999999999999996


We see that the answer is not exactly 0.2! Floating-point numbers are stored as binary ones and zeros in computer memory, and there is only a finite amount of memory available to represent them. As a result, Python (and any other programming languages) use tricks and approximations to represent floating-point numbers. This can sometimes lead to unexpected rounding errors that you may want to be aware of.

Augmented Assignments

In Python, augmented assignments are a shorthand notation that combines an operation with assignment. Instead of explicitly writing an operation followed by an assignment statement, you can use augmented assignments to make the code more concise. The general form of an augmented assignment is:

x <operator>= y


Where <operator> can be any binary arithmetic operator. For example:

x = 5
x = x + 3

y = 5
y += 3 

x == y
## True


In this example, both x = x + 3 and y += 3 achieve the same result: adding 3 to the variable x and y, respectively.


Comparison Operators on Integers and Floats

Comparison operators in Python are used to compare values and return a Boolean result (either True or False). When applied to integers and floats, these operators evaluate the relationships between the numeric values. For example:

x = 5
y = 5.0

result1 = x == y # True
print(result1)
## True
result2 = x != y # False
print(result2)
## False


When using these operators with integers and floats, Python performs automatic type coercion if needed. For example, when comparing an integer and a float, Python will consider them as the same if their values are equal. Understanding how these operators work is fundamental for making decisions and implementing conditional logic in your Python programs.


Booleans

In programming, a Boolean data type represents logical values. It can only have one of two possible values: True or False. Boolean values are commonly used in programming to make decisions or to control the flow of a program through conditional statements.

In Python, Boolean is an immutable data type, and is equivalent to False is 0, 0.0, None, '', [], {}, (), set(). Other than these, any values are considered as True. For example, a character string "False" is considered as True, as it is not an empty character. Likewise, a string with a space value is also considered as True.

bool('False') # Will return `True`
## True


bool(' ') # Will return `True`
## True


bool('') # Will return `False`
## False


11 - False # 11 - 0
## 11


11 + True # 11 + 1
## 12


We can apply logical operators to Boolean data.

True or False # Returns `True` if at least one of operands is `True`
## True
True and False # Returns `True` if both operands are `True`
## False
not True # Returns `False`
## False
not False # Returns `True`
## True


In Python, the precedence order of logical operators is as follows (from highest to lowest):

  1. Parentheses
  2. Not
  3. And
  4. Or

So, when multiple logical operators are used in an expression, Python will first evaluate any expressions inside parentheses, then any expressions following not operator, then any expressions following and operator, and finally any expressions following or operator.

False or not True and True # False
## False


False and not True or True # True
## True



Commonly Used Functions to Handle Numeric Data

These functions provide essential tools to process numeric data, from absolute value calculations to rounding and conversion between different numeric types.

Syntax Description
abs(x) Returns absolute value of x
divmod(x,y) Returns quotient and remainder after x/y
pow(x,y) Returns x**y
pow(x,y,z) Returns (x**y)%z
round(x,n) Returns x rounded to n-th decimals
int(x) Convert x to int
float(x) Convert x to float
max(x,y) Compare x and y and returns greater value
min(x,y) Compare x and y and returns smaller value

Post a Comment

0 Comments