How To Print Infinite Numbers In Python

In this tutorial, we will learn how to print an infinite series of numbers using the Python programming language. This could come in handy if you are developing a script that needs to generate a constantly updating sequence of numbers, such as prime numbers or Fibonacci numbers.

Step 1: Import necessary Python modules

First, we will need to import the necessary Python modules to accomplish our goal. The itertools module will be used for creating iterators for generating an infinite sequence of numbers.

Step 2: Define the infinite generator function

Next, we will define a generator function called infinite_numbers. This function will yield an infinite series of numbers, starting from 1.

Step 3: Print the infinite numbers using itertools.islice()

Finally, we will use the islice() function from the itertools module to print a specified number of infinite numbers. This allows us to print a slice of the infinite sequence in a controlled manner.

This code will print the first 10 numbers of the infinite sequence.


You can set the numbers_to_print variable to any positive integer value to print a different number of infinite numbers.

Full code

Here is the full code for printing an infinite series of numbers in Python:


In this tutorial, we learned how to print an infinite series of numbers in Python. By using a simple generator function and the itertools module, you can easily create and control the output of an infinite sequence of numbers for various applications in your Python programs.