Learning Management Platform for Written Tutorial Series.

Python 3 Numbers - Learn how to work with number data types

Python 3 Numbers - Learn how to work with number data types

Python Numbers

In the previous lesson, we explored the concepts of numeric variables. In this tutorial, we will look at the same concept but take it a step further. We will look at the actions that can be performed using numbers and some of the built-in functions that we can use to perform operations of numbers.

Topics to be covered

We will cover the following topics in this section.

  • Numeric variables
  • Arithmetic operations
  • Type conversion
  • Numeric functions

Numeric Variables

In this section, we will create variables of the following types;

  • int - these are numbers that do not contain decimal points. For example, 3,4,5 are examples of integers.
  • float these are numbers that contain decimal points. For example, 3.0,4.0,5.0 are examples of floating types.
  • complex - complex numbers are an extension of the real numbers system expressed as the sum of the real and imaginary numbers. The imaginary part is written with a j at the end. Let's consider the expression 1 + 3j. 1 is the real number and 3j is imaginary. We know it's imaginary because of the j that is placed at the end.

Let's now work with a practical example that will create the variables to hold the above numbers.

Create a new directory numbers

Add the following file to your directory app.py

Add the following code to app.py

int_var = -6; float_var = 1.3 ; complex_var = 1 + 3j

print(f'The type of int_var is {type(int_var)} and it has a value of {int_var}')
print(f'The type of float_var is {type(float_var)} and it has a value of {float_var}')
print(f'The type of complex_var is {type(complex_var)} and it has a value of {complex_var}')
print(f'The complex_var has a real value of {complex_var.real} and imaginary part of {complex_var.imag}')

HERE,

  • int_var = -6; float_var = 1.3 ; complex_var = 1 + 3j defines three variables that are of data types int, float and complex.
  • print(f'...' uses formatted string to print the variable type by calling the built-in type function and passing in the value of the variable. On complex number variable, the variable object has two methods namely real and imag that allow us to retrieve the real and imaginary parts of our complex variables.

The above code produces the following results

The type of int_var is <class 'int'> and it has a value of -6
The type of float_var is <class 'float'> and it has a value of 1.3
The type of complex_var is <class 'complex'> and it has a value of (1+3j)
The complex_var has a real value of 1.0 and imaginary part of 3.0

As you can see from this example, the numeric type of the variable is determined by the value that has been assigned to it.

Arithmetic operations

Let's now at some of the arithmetic operations that we can perform on numbers.

hours = 20.6
hourly_rate = 120.00

total_wages = hours * hourly_rate

print(f'The total charge for {hours} hours at the rate of {hourly_rate} is {total_wages:,}')

HERE,

  • hours = 20.6 defines a variable that holds the number of hours worked
  • hourly_rate = 120.00 defines the hourly rate
  • total_wages = hours * hourly_rate multiplies the hours by the hourly_rate then assigns the result to the variable total_wages
  • print(f'The total charge for {hours} hours at the rate of {hourly_rate} is {total_wages:,}') prints the total_wages and the parameters used to arrive at the wages.

The above code produces the following results

The total charge for 20.6 hours at the rate of 120.0 is 2,472.0

Arithmetic operators order of precedence

We can perform addition, subtraction, multiplication, and division.

Let's consider the following expression

result = 7 + 1 * 2 / 4

print(result)

Reading the expression the natural human way, we can arrive at the following answer

7 + 1 = 8

We then multiply 8 * 2 to get 16

We finish by dividing the result 16 by 4 and we get 4 as the result.

in reality when we obey mathematical laws religiously, we arrive at the following answer

7.5

This is because python executes the expression based of the order of precedence. When I was a little boy at school we were taught the mnemonic BODMAS - Brackets of Division, Multiplication, Addition and Subtraction. That is the order of precedence

Let's now apply to our above expression.

Brackets come first but we don't have them in our expression so we move on

Division comes after brackets so we divide 2 / 4 to get 0.5

Multiplication comes after division so we multiply 1 with 0.5 and we get the same result

Addition comes after multiplication so we add 7 to 0.5 to get our result 7.5

It's very important that you keep the order of precedence in mind when writing arithmetic expressions.

Type conversion

Some times its necessary to convert one type of data to another. For example, you might want to convert a string to a numeric type like int or float

Python supports two types of conversions namely implicit (which is automatic) or explicit (which is deliberate)

Let's now work with a practical example the following code

Add the following code to app.py

first_number = 1
second_number = 2.0

total = first_number + second_number

print(f'The sum of {first_number} {type(first_number)} and {second_number} {type(second_number)} is {total} {type(total)}')

Executing the above code produces the following results

The sum of 1 <class 'int'> and 2.0 <class 'float'> is 3.0 <class 'float'>

Note whenever you write expressions that have ints and floats, float the result is implicitly converted to float

If we want to explicitly convert the results to an int, then we can use the built-in int function like so

total = int(first_number + second_number)

The above expression produces the following results

The sum of 1 <class 'int'> and 2.0 <class 'float'> is 3 <class 'int'>

Let's now create a simple interactive console application that will ask the user to enter the bill amount then we will calculate the value added tax (VAT).

Create a new file vat.py

Add the following code

header = "Value Added Tax (VAT) Calculator"

print(header)
print('*' * len(header))
print('')

vat_rate = 0.18
amount = input('Enter the total amount: ')
vat_charge = amount * vat_rate

print(f'The VAT is {vat_charge:,} ({vat_rate * 100}% of {amount:,})')

Run the following command to execute the code

python3 vat.py

You will get an error message similar to the following

Value Added Tax (VAT) Calculator
********************************

Enter the total amount: 45000
Traceback (most recent call last):
  File "vat.py", line 9, in <module>
    vat_charge = amount * vat_rate
TypeError: can't multiply sequence by non-int of type 'float'

We are getting the above error because even if the user entered 45000 which is an int, python treats the value as a string. Let's now convert the amount to a float.

Modify the expression to the following code

header = "Value Added Tax (VAT) Calculator"

print(header)
print('*' * len(header))
print('')

vat_rate = 0.18
amount = input('Enter the total amount: ')
amount = float(amount)
vat_charge = amount * vat_rate

print(f'The VAT is {vat_charge:,} ({vat_rate * 100}% of {amount:,})')

HERE,

  • amount = float(amount) we are using the built-in function float to convert the string value '45000' to a float 45000.0. The arithmetic then works without any errors. Executing the above code should give you the following results.
Value Added Tax (VAT) Calculator
********************************

Enter the total amount: 45000
The VAT is 8100.0 (18.0% of 45,000.0)

Numeric functions

Let's now look at some of the built-in functions that we can use when dealing with numbers.

How to generate a random number in python

Create a new file numbers.py

Add the following code

import random

print(f'Python random module generated {random.random()}')

Executing the above code produces results similar to the following.

Python random module generated 0.21985951939907356

How to sum all numbers in a list in python

Let's say we have a list of numbers from 1 to 5 and we want to sum all of them, we can use the sum function to do that.

numbers = [1,2,3,4,5]

print(f'The sum is {sum(numbers)}')

HERE,

  • sum(numbers) calls the sum function passing in the list of numbers as the parameter.

Executing the above code produces the following results

The sum is 15

How to find the minimum number in a list in python

we can use the following code to find the minimum number in our list

numbers = [1,2,3,4,5]

print(f'The min is {min(numbers)}')

HERE,

  • min(numbers) calls the min function passing in the list variable numbers as the argument.

executing the above code produces the following results

The min is 1

How to find the maximum number in a list in python

The following code find the maximum number in a list

numbers = [1,2,3,4,5]

print(f'The max is {max(numbers)}')

HERE,

  • max(numbers) uses the max function to get the largest number in the list numbers

Executing the above code produces the following results

The max is 5

Summary

Numbers are numeric data types. Python supports integers, floats and complex numbers. You can perform arithmetic operations on numbers and take advantage of many built-in function to do more without writing custom code.

What next?

If you enjoyed this lesson then show us your appreciation by creating a free accounts on our site. As always we appreciate your comments down below.


...