DEV Community

Cover image for Python Tutorial: Numbers - A beginner's Guide to Understanding Numeric Data Types in Python
David Fabusuyi
David Fabusuyi

Posted on • Updated on

Python Tutorial: Numbers - A beginner's Guide to Understanding Numeric Data Types in Python

Data in Python takes the form of objects, either those that Python comes with pre-built or those that we generate using Python tools or other programming languages. As a result, the foundation of every Python program is an object.

We'll examine Python's numeric type in-depth in this tutorial. Numerical Literals, arithmetic operators, comparison operators, built-in numeric tools (functions and modules), operator precedence, and other ideas will be covered.

TABLE OF CONTENTS

Fundamentals of Numeric Types

In Python, floats and integers are most frequently used to represent numeric data types. Python does, however, include a range of numeric built-ins and modules for more difficult operations, including complex numbers, rational fraction numbers, and more.

Numeric Literals

As previously mentioned, Python's primary methods for representing numbers are integers and floats. Integers are whole numbers that can either be positive or negative, but floats, also known as floating-point numbers, are numbers that contain a fractional part.

This tutorial will mostly focus on integers and floats even though Python also allows us to create integers using hexadecimal, octal, and binary literals.

For a better grasp of the fundamental numerical Literals, see the example below.

num_1 = 10 # An Integer
num_2 = 1.23 # A floating-point number
num_3 = 2 + 3j # A complex number literal 
Enter fullscreen mode Exit fullscreen mode

Built-in Numeric Tools

Since number types are objects, Python offers a collection of tools for manipulating them. These tools include Expression operators (Arithmetic operators, comparison operators, etc.), Built-in mathematical functions (abs, round, pow, int, etc.), Built-in modules (math, random, etc.)

In the next section and a few more sections, we will see some of these built-in numeric tools in action.

To start with, let's see how to work with expression operators.

Python Expression Operators

An expression is basically a combination of objects and operators that are used to manipulate these objects.

In the case of numbers, an expression is a combination of numbers and operators that computes a value when executed by Python.

Expressions are represented using the normal mathematical operator symbols and notations.

Listed below are some of the basic expression operators available in Python.

  • Arithmetic Operators
  • Comparison Operators
  • Object identity tests
  • Membership tests

Understanding Python's numeric objects, expressions, and most likely all other types of objects is best accomplished through using them. Let's begin using these expressions right away so that we can move on

Arithmetic Operators

Arithmetic operators are used to perform the normal, basic math.

Listed below are the arithmetic operators available in Python

  • Addition
  • Subtraction
  • Multiplication
  • Division (True and Floor)
  • Exponentiation (Power)
  • Modulus (Remainder)

The code below illustrates how these operators are used. I've also added comments also to give explanations.

# Addition 
print(3 + 2) # Adds 3 and 2 together and prints 5
5 

# Subtraction
print(3 - 2) # Subtracts 2 from 3 and prints 1
1

# Multiplication
print(3 * 2) # Multiplies 3 by 2 and prints 6
6

# Division
print(3 / 2) # Performs true division and prints 1.5
1.5
print(3 // 2) # Performs floor division and prints 1.0
1 # Fractional part gets truncated

# Exponentiation
print(3 ** 2) # Raises 3 to the power of 2 and prints 9
9

# Remainder
print(3 % 2) # Prints the remainder of dividing 3 by 2 using the Modulus operator
1
Enter fullscreen mode Exit fullscreen mode

However, there are a few things to note during division.

  • The single forward slash (x / y) performs true division, regardless of types. That is, it keeps remainders either you're dividing integers or floating-point numbers.
print(3 / 3) # Prints 1.0
1.0

print(3 / 2) # Prints 1.5
1.5

print(3 / 2.0) # Prints 1.5
1.5
Enter fullscreen mode Exit fullscreen mode
  • The double forward slashes (x // y) performs floor division, regardless of types. This operator always truncates fractional remainders to their floor, either you're dividing integers or floating-point numbers.

  • The //, when used, truncates the remainder and returns an integer for integer operands, or returns a float if any operand is a float.

print(3 // 2) # Prints 1
1

print(3 // 2.0) # Prints 1.0
1.0
Enter fullscreen mode Exit fullscreen mode

Operator Precedence

A more complex expression can be created in Python by combining multiple operators. For instance

x + y / z - k
Enter fullscreen mode Exit fullscreen mode

What will be the answer when these alphabets (variables) are replaced by real numbers? For instance

print(4 + 2 / 3- 1)
Enter fullscreen mode Exit fullscreen mode

You may be expecting that python will carry out this operation from left to right and 1 will be printed out.

Well, that's not how it works.

So how does python know which operation to perform first? This is where operator precedence comes in.

There are some rules known as precedence rules, which helps python to group complex expressions into parts. This rule determines which part of the expression is executed first.

These parts of the expression is executed in order of precedence from the highest to the lowest. That is, parts with an operator which have a higher precedence is executed first.

The following operators are arranged in their increasing order of precedence.

Addition -> Subtraction -> Multiplication -> Modulus (Remainder) -> Division

For instance

print(8 + 3 - 5 % 3 - 4 / 2 * 3)
Enter fullscreen mode Exit fullscreen mode

3.0 is printed out.

Division first, followed by remainder, multiplication, subtraction and addition.

Trace the steps through this operation to gain a better understanding of how operator precedence works.

However, you can manually instruct Python as to which portion of an expression should be executed first.

This is done by grouping parts of expressions within parentheses. This way, you'll override Python's precedence rules.

For instance

result = (4 + 2) / 2
print(result) # Prints 4
4
Enter fullscreen mode Exit fullscreen mode

Wrapping 4+2 in parentheses will force Python to evaluate the addition operation first, even though division has a higher precedence.

Incrementing and Decrementing values

The idea of working with arithmetic operators can be used to increment and decrement values.

For instance

x = 1

# Incrementing 
x = x + 1 # Adds 1 to x
print(x) # Prints 2
2

# Line 4 can also be written as 
x += 1

# Decrementing 
x = x - 1
# or
x -= 1
Enter fullscreen mode Exit fullscreen mode

These forms of incrementing/decrementing can also be used with other operators.

x = 6

x *= 2 # x = x * 2. Prints 12 (6 * 2)
x /= 3 # x = x / 3. Prints 4.0 (12 / 3)
x %= 2 # x = x % 2. Prints 0.0 (4 % 2)
Enter fullscreen mode Exit fullscreen mode

Decrementing or incrementing values comes in handy mostly when working with loops.

Modulus (Remainder) are mostly used to check if a value is even or odd.

For instance

a = 2
b = 3
print(a % 2) # Prints 0 because 2 divides 2 completely 
print(b % 3) # Prints 1
Enter fullscreen mode Exit fullscreen mode

Even numbers will return 0 when they are divided by 2.
Odd numbers will return 1 when they are divided by 2.

You'll see these operators and operator expression a lot more in future topics when you start to write more complex programs. However, it is important that you're given a basic introduction.

Comparison Operators

Python also supports comparison of numbers. Comparison Operators compares the relative magnitudes of their operands and returns a Boolean as a result of the comparison.

Listed below are the comparison operators available in Python

  • Equal to ( == )
  • Not equal ( != )
  • Greater than ( > )
  • Less than ( < )
  • Greater than or Equal to ( >= )
  • Less than or equal to ( <= )

The best way to understand how these operators work is by seeing them in action.

The code below illustrates how these operators work. I've also added comments explaining how they work.

# Equal
print(2 == 2) # Prints True since 2 is equal to 2
True
print(3 == 2) # Prints False because 3 is not equal to 2
False

# Not equal
print(2 != 2) # Prints False because 2 is equal to 2
False
print(3 != 2) # Prints True
True

# Greater than
print(2 > 2) # Prints False
False
print(3 > 2) # Prints True
True

# Less than
print(2 < 2) # Prints False
False
print(2 < 3) # Prints True
True

# Greater or equal to
# Checks if a number is greater than or equal to the other
# Returns True if at least one condition is True
# Returns False if both conditions are False
print(2 >= 2) # Prints True because 2 is equal to 2
True
print(3 >= 2) # Prints True
True
print(1 >= 2) # Prints False
False

# Less than or equal to
# Checks if a number is lesser than or equal to the other
# Returns True if at least one condition is True
# Returns False if both conditions are False
print(2 <= 2) # Prints True
True
print(3 <= 2) # Prints False
False
print(1 <= 2) # Prints True
True
Enter fullscreen mode Exit fullscreen mode

Interestingly, Comparison operators can also be combined together to perform more complex tests.

For instance

a = 1
b = 2
c = 3
print(a < b < c) # Print True because a < b and b < c
print(a < b > c) # Prints False because a < b but b is not > c
Enter fullscreen mode Exit fullscreen mode

Built-in Functions

In addition to the built-in expression operators, Python also provides built-in functions for manipulating numeric object types.

Some of these functions include; pow(), abs(), min(), max(), round(), and int().

Let's see these functions in action.

The code below illustrates how these built-in functions are used in python. I've also added comments to give explanations.

# Absolute value
print(abs(-3)) # Prints 3
3

# Exponentiation (power)
print(pow(3, 3)) # 3 ** 3. Prints 9
9

# Round
print(round(3.567)) # Prints 4
4

# Minimum value
print(min(5, 3, 6, 4)) # Prints 3
3

# Maximum value
print(max(1, 4, 5, 3)) # Prints 5
5

# Summation
print(sum(1, 2, 3)) # Adds all the values and prints 6
6

# Truncate
print(int(3.47)) # Prints 3
3
Enter fullscreen mode Exit fullscreen mode

Built-in Modules

The math and random modules provided by Python, can also be used for numeric processing. These modules contains functions that can be used to perform certain operations on numbers.

These modules must be imported first before they can be used.

Let's see some examples of how these modules work

Math module

The math module contains functions that are used to process numeric object types.

import math

# Common constants
print(math.pi) 
3.141592653589793
print(math.e)
2.718281828459045

# Square root
math.sqrt(49)
7.0

# Floor
math.floor(3.56)
3
math.floor(-3.56) # Floors to the next-lower integer
-4

# Truncate decimal digits
math.trunc(3.56)
3
math.trunc(-3.56)
-3
Enter fullscreen mode Exit fullscreen mode

Random module

The random module is a built-in module which provides tools for picking a random floating-point number between 0 and 1, selecting a random integer between two numbers, and also for choosing an item at random from a sequence.

Let's see an example of how this module works

import random

# Picking a random floating-point number between 0 and 1
print(random.random())
0.812811807707059
print(random.random())
0.1516146750767553

# Selecting a random integer between two numbers 
print(random.randint(1, 5))
5
print(random.randint(1, 5))
3
print(random.randint(1, 5))
4

# Choosing an item at random from a sequence 
names = ['john', 'joe', 'smith',  'ham', 'foo', 'spam']
print(random.choice(name))
'joe'
print(random.choice(name))
'ham'
print(random.choice(name))
'foo'
Enter fullscreen mode Exit fullscreen mode

Number Display Formats

One last thing I'd like to show you is how to manually specify how numbers are displayed. To format a number for output, use the built-in format() function.

To get a better understanding of this concept, see the code below

x = 1234.56789
y = 1234.56789

# Two decimal places of accuracy 
print(format(x, '0.2f')) # Suitable when working with just one variable
'1234.57'

# Another method
print('{:0.2f} | {:0.3f}'.format(x, y)) # Suitable when working with more than one variable 
'1234.57 | 1234.568' # Rounds x to 2 decimal places of accuracy and y to 3 decimal places of accuracy 

# Exponentiation notation
print(format(x, 'e')) # Change the f to e
'1.234568e+03
Enter fullscreen mode Exit fullscreen mode

Final Thoughts

Python offers a range of numeric data types that allows for precise and efficient numerical computations. These data types include integers, floating-point numbers, complex numbers, and more.

Python's built-in numeric data types make it a powerful tool for scientific computing, data analysis, and many other applications and in this article we've taken a look at how numbers works in Python.

In the course of writing this article, I've learned a lot and I hope you do too.

That's it for this article. If you have any question or you think there's something you want me to add to this article or upcoming ones, please drop them in the comment section below.

And If you like this article, please follow for more and don't forget to share with others who might find it helpful.

Finally, I'd like to connect with you on LinkedIn | Twitter | GitHub | YouTube.

Thanks for reading. See you in the next one!

Top comments (5)

Collapse
 
jayywestty profile image
Juwon?🍀

This is nice

Collapse
 
techwithdavid profile image
David Fabusuyi

Thanks, Juwon.

Collapse
 
techwithdavid profile image
David Fabusuyi • Edited

Thank you, Temitope.

Collapse
 
stankukucka profile image
Stan Kukučka

@techwithdavid great summary and new suggestion appeared for me

Collapse
 
techwithdavid profile image
David Fabusuyi

Thank you, Stan. Glad it helped