How To Read Numbers In Python

Reading numerical data from different sources is a common requirement for programming tasks. This tutorial will focus on understanding how to read numbers in Python, a powerful and versatile programming language.

In this tutorial, we will go through the following steps:

  1. Using the input() function to read numbers
  2. Reading integers from a file
  3. Reading floating-point numbers from a file
  4. Reading numerical data from a comma-separated values (CSV) file

We will cover the necessary Python functions, techniques, and libraries, specifically, Python Built-in Functions and the CSV library.

Step 1: Using input() function to read numbers

The input() function is used to read user input from the console. It returns the input as a string, so you need to convert it to an integer or float depending on the required number format.

To read an integer, for example:

To read a floating-point number:

Step 2: Reading integers from a file

We will now read integers from a file named numbers.txt containing one number per line. Using Python’s built-in file handling functions, you can open the file, loop through its lines, and convert each line to an integer.

Example content of a file numbers.txt:

10
15
25
35
45

Read the numbers from the file and save them into a list:

Step 3: Reading floating-point numbers from a file

The process of reading floating-point numbers from a file is very similar to reading integers. Just replace the int() function with the float() function.

Example content of a file floating_numbers.txt:

1.25
3.14
5.67
7.89
9.01

Read the floating-point numbers from the file and save them into a list:

Step 4: Reading numerical data from a comma-separated values (CSV) file

We will use Python’s CSV library to read numerical data from a CSV file. Here’s an example CSV file (data.csv) containing numbers:

1, 2, 3
4, 5, 6
7, 8, 9

To read the data in this file and save it into a list of lists:

Full code

Conclusion

In this tutorial, you have learned different ways of reading numbers in Python, namely using the input() function, reading integers and floating-point numbers from a file, as well as reading numerical data from a CSV file using Python’s CSV library.

With these concepts at your disposal, you should be ready to tackle a variety of Python programming tasks involving numerical data processing.