How to print 1 to 100 in Python
Learn how to print numbers 1 to 100 in Python. Explore various methods, tips, real-world uses, and common error debugging.
.png)
A classic Python exercise is to print numbers from 1 to 100. This task introduces fundamental concepts like loops and the range() function, essential skills for any developer to master.
You'll learn several methods to complete this task, from simple for loops to more concise one-liners. You'll also get practical tips, see real-world applications, and receive advice to debug common errors.
Basic for loop to print numbers 1 to 100
for i in range(1, 101):
print(i)--OUTPUT--1
2
3
...
98
99
100
This for loop offers a direct and readable solution. The core of this method is the range() function, which is memory-efficient because it generates numbers as needed instead of storing the entire sequence at once.
- The first parameter,
1, sets the starting point of the sequence. - The second parameter,
101, is the exclusive endpoint, ensuring the loop's final number is100.
Basic approaches to printing numbers
While the for loop is a solid starting point, Python also provides more compact and flexible methods for printing the same sequence of numbers.
Using print() with unpacking
print(*range(1, 101))--OUTPUT--1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 ... 100
This one-liner offers a more compact solution. The key is the asterisk *, Python's unpacking operator. It effectively "unpacks" the numbers from the range() object, passing them as individual arguments to the print() function.
- The
print()function then displays each argument on the same line, separated by a space by default. - It's a handy method for creating a quick, space-separated list without needing a multi-line loop.
Using list comprehension
[print(num) for num in range(1, 101)]--OUTPUT--1
2
3
...
98
99
100
List comprehension is a Pythonic way to create lists in a single, readable line. While it's typically used to build a new list, here it's used to run the print() function for each number in the sequence.
- The main action is the side effect of printing each number on a new line.
- Because
print()returnsNone, this code also creates a list containing 100Nonevalues, which is something to be aware of.
Using a while loop with formatted output
num = 0
while num < 100:
num += 1
print(f"Number {num}")--OUTPUT--Number 1
Number 2
Number 3
...
Number 98
Number 99
Number 100
A while loop gives you more manual control over the iteration. Unlike a for loop, you're responsible for initializing and updating the counter variable yourself. In this example, num starts at 0, and the loop continues as long as the condition num < 100 is true.
- The counter is incremented with
num += 1at the start of each loop, ensuring the count begins at 1. - Using an f-string with
print()allows you to easily embed the variable directly into the output string for custom formatting.
Advanced techniques for printing sequences
With the basics covered, you can gain more control over memory and output using advanced techniques like generator functions, itertools, and the join() with map() pattern.
Using a generator function
def number_generator(start, end):
current = start
while current <= end:
yield current
current += 1
for num in number_generator(1, 100):
print(num)--OUTPUT--1
2
3
...
98
99
100
A generator function like number_generator offers a custom, memory-efficient way to produce a sequence. It uses the yield keyword to produce one value at a time, pausing its state until the next value is requested, rather than building an entire list in memory.
- The
yieldkeyword turns the function into a generator that can be paused and resumed. - This approach is highly memory-efficient because it generates numbers on the fly, making it ideal for large datasets.
- The
forloop iterates over the generator, requesting each number just as it's needed.
Printing in chunks with itertools
import itertools
for i in range(0, 100, 10):
print(list(itertools.islice(range(1, 101), i, i+10)))--OUTPUT--[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
[11, 12, 13, 14, 15, 16, 17, 18, 19, 20]
...
[91, 92, 93, 94, 95, 96, 97, 98, 99, 100]
The itertools module provides powerful tools for working with sequences. This method uses itertools.islice() to process the numbers in batches. It's a memory-efficient way to handle large datasets because it doesn't create a full copy of the data.
- The outer
forloop iterates in steps of 10, setting the starting index for each chunk. itertools.islice()then grabs a slice of 10 numbers from the mainrange(1, 101)iterator.- Finally, the
list()function converts each slice iterator into a list that can be printed.
Using join() with map() for efficient string conversion
print('\n'.join(map(str, range(1, 101))))--OUTPUT--1
2
3
...
98
99
100
This one-liner is a highly efficient way to generate the output. It's a classic Python pattern that combines the map() function with the string join() method to build a single string before printing.
- The
map(str, range(1, 101))function converts each number to a string as it's needed, which is more memory-efficient than creating a temporary list. - Then,
'\n'.join()takes these strings and stitches them together into one large string, using a newline character as the separator. - The final string is then passed to
print()to be displayed all at once.
Move faster with Replit
Replit is an AI-powered development platform that transforms natural language into working applications. Describe what you want to build, and Replit Agent creates it—complete with databases, APIs, and deployment.
For the sequence-generating techniques you've just seen, Replit Agent can turn them into production-ready tools. It understands how to apply concepts like memory-efficient generators or the itertools module to build robust applications.
- Build a data processing tool that uses
itertools.isliceto paginate and display large lists of items without loading everything into memory. - Create a utility that generates a specific number of unique test files or database entries using a custom generator function.
- Deploy a simple API that returns a numbered list as a JSON array, built efficiently with
map()andstr().
Describe your app idea, and Replit Agent will write the code, test it, and fix issues automatically, all within your browser.
Common errors and challenges
Even simple tasks have pitfalls; here’s how to navigate common errors like off-by-one mistakes, infinite loops, and type mismatches.
A frequent stumble for newcomers is the off-by-one error with the range() function. This happens because its second argument is exclusive, meaning it stops before reaching that number. Using range(1, 100) will only print numbers up to 99.
- To fix this and include 100, you must set the endpoint to
101. - The correct implementation is
range(1, 101), which generates numbers from 1 up to, but not including, 101.
Unlike for loops, while loops require you to manage the counter yourself, making them prone to running forever. An infinite loop occurs if the condition that's supposed to stop the loop never becomes false. This usually happens when you forget to increment the counter variable, like num += 1, inside the loop.
- Without this update, the counter never changes, and the loop's condition remains true indefinitely.
- Always ensure your
whileloop includes logic that moves it closer to its exit condition with each pass.
You'll hit a TypeError if you try to combine numbers into a single string using the join() method. This is because join() is a string method that expects an iterable of strings, not integers. You can't directly pass it the numbers produced by range().
- The solution is to convert each number into a string before joining them.
- This is done efficiently using the
map()function, as inmap(str, range(1, 101)), which applies thestr()function to every item.
Fixing off-by-one errors with range()
The range() function is a frequent source of off-by-one errors. This happens because it stops generating numbers before reaching its endpoint. For example, range(10) doesn't actually include the number 10. See what happens in the code below.
# Trying to print numbers 1 to 10
for i in range(10):
print(i)
Because range(10) starts at 0 by default, this code prints numbers 0 through 9 instead of the intended 1 to 10. See the corrected implementation below for the proper approach.
# Correctly printing numbers 1 to 10
for i in range(1, 11):
print(i)
The corrected code uses range(1, 11) to generate the intended sequence. This works because the range() function includes its starting number but stops one number before its endpoint, making the final value exclusive.
- The first argument,
1, is the inclusive start. - The second argument,
11, is the exclusive stop, so the loop ends after printing10.
This off-by-one behavior is common, so always double-check your boundaries when looping or slicing.
Preventing infinite loops when using while
The flexibility of a while loop comes with a catch—you must ensure it has a clear exit path. Forgetting to update the counter variable inside the loop is a classic mistake that traps it in an infinite cycle. Observe this common error in the code below.
count = 1
while count <= 5:
print(count)
# Forgot to increment count
Because the count variable never changes from its initial value of 1, the condition count <= 5 is always true. This creates an infinite loop. See the corrected implementation below.
count = 1
while count <= 5:
print(count)
count += 1
The fix is simple but crucial: adding count += 1 ensures the loop makes progress. This line increments the counter with each pass, so the condition count <= 5 eventually becomes false, and the loop terminates correctly.
- Without an update to the counter, the loop's condition never changes, causing it to run forever.
- Always confirm that your
whileloops include logic that moves them toward their exit condition.
Resolving type errors when joining numbers
You can't use the join() method on a sequence of numbers without getting a TypeError. Since join() only works with strings, you must convert the numbers first. The code below demonstrates the error you'll encounter if you forget this step.
numbers = range(1, 6)
print('\n'.join(numbers))
The join() method expects a sequence of strings, but the range(1, 6) object provides integers. This mismatch causes a TypeError. The following example shows how to properly prepare the numbers for joining.
numbers = range(1, 6)
print('\n'.join(map(str, numbers)))
The fix uses the map() function to apply str() to each number from the range(). This creates an iterator that converts each integer into a string just in time, allowing join() to successfully stitch them together with a newline separator.
- This
map(str, ...)pattern is memory-efficient because it avoids creating a temporary list of strings. - You'll encounter this
TypeErrorwhenever you try to join a sequence containing non-string items.
Real-world applications
The principles behind printing a sequence of numbers are the same ones you'll use to build practical tools like multiplication tables and progress bars.
Creating a multiplication table with range() and formatted strings
By nesting two range() loops and using f-string formatting for alignment, you can easily create a clean multiplication table.
for i in range(1, 11):
row = " ".join(f"{i*j:3d}" for j in range(1, 11))
print(row)
This code efficiently builds the table one line at a time. For each number i from 1 to 10, it creates a complete row string. It does this with a generator expression that produces each calculated value (i*j) on the fly.
- The expression uses an f-string,
f"{...:3d}", to format each product into a string that is exactly three characters long, adding padding if needed. - The
" ".join()method then takes these formatted strings and connects them with a single space in between. - Finally, the complete row string is printed.
Building a command-line progress bar with sys.stdout
By controlling the output stream with sys.stdout.write() and the carriage return character (\r), you can create a dynamic progress bar that updates on a single line.
import time
import sys
for i in range(0, 101, 5):
progress = "█" * (i // 5) + "░" * (20 - i // 5)
sys.stdout.write(f"\r|{progress}| {i}%")
sys.stdout.flush()
time.sleep(0.1)
print("\nTask completed!")
This code animates a progress bar directly in your terminal. The loop uses range(0, 101, 5) to advance the percentage in steps of five, redrawing the bar on the same line with each update.
- The visual bar itself is a string built with multiplication. The expression
i // 5calculates how many of the 20 total blocks should be filled with the█character. sys.stdout.flush()forces the update to display instantly, andtime.sleep(0.1)pauses the animation so it's slow enough for you to see.
Get started with Replit
Put your skills to work. Tell Replit Agent to "build a command-line tool that generates a multiplication table" or "create a web app that converts Celsius to Fahrenheit for a specific range."
The agent writes the code, tests for errors, and deploys your app, handling the heavy lifting so you can focus on your idea. Start building with Replit.
Create and deploy websites, automations, internal tools, data pipelines and more in any programming language without setup, downloads or extra tools. All in a single cloud workspace with AI built in.
Create & deploy websites, automations, internal tools, data pipelines and more in any programming language without setup, downloads or extra tools. All in a single cloud workspace with AI built in.


.png)
.png)