This tutorial will guide you through the process of printing numbers with spaces in between in Python. This might seem like a simple task, but it can often puzzle beginners.
It’s important to understand how to generate output according to our requirements, as it not only improves code readability but also the presentation of the data for further analysis.
1. Using a For Loop
The simplest way to print numbers with spaces in Python is by using a for loop along with the str() and print() functions.
1 2 |
for i in range(1, 11): print(str(i) + ' ', end='') |
You will see the following output:
1 2 3 4 5 6 7 8 9 10
2. Using the * Operator in the Print Function
Python’s print() function allows us to print each element of a sequence separated by a delimiter of our choice by using the * operator. So we can create a range and print it:
1 |
print(*range(1, 11)) |
The output will be:
1 2 3 4 5 6 7 8 9 10
Full Code
1 2 3 4 5 6 |
for i in range(1, 11): print(str(i) + ' ', end='') print('\n') print(*range(1, 11)) |
Conclusion
In this tutorial, we’ve learned two different ways of printing numbers with spaces in Python. The first method involves looping over a range of numbers, converting each number to a string, and then using concatenation to add a space before printing the number.
The second method leverages Python’s print function to directly print each number of the range separated by a space. Both methods give the same output, allowing us to choose based on personal preference or the specific requirements of your problem.