Skip to content

Print 1 to n in Python

  • by

To print numbers from 1 to n in Python, you can use a simple loop. Here’s an example using a for loop:

n = int(input("Enter a number: "))

for i in range(1, n+1):
    print(i)

In this code, range(1, n+1) generates a sequence of numbers starting from 1 up to n (inclusive), and the for loop iterates through each number in the range, printing it.

Alternatively, if you want to print numbers in a single line separated by spaces, you can use the end parameter of the print function:

n = int(input("Enter a number: "))

for i in range(1, n+1):
    print(i, end=' ')

This will print the numbers from 1 to n separated by spaces on the same line.

Another example Print 1 to n in Python

A simple example code to print numbers from N to 1 using a while loop:

N = int(input("Enter a number: "))
i = N

while i >= 1:
    print(i)
    i -= 1

Output:

Print 1 to n in Python

In this program, you input a number N, and the while loop starts from N and decrements i by 1 in each iteration until i becomes less than 1. This prints the numbers from N down to 1.

Feel free to replace the input method with a fixed value of N if you want to avoid user input.

How to print 1 to n in Python in a single line?

Answer: You can use the print() function along with a generator expression and the end parameter to achieve this in a single line. Here’s how you can print the numbers from 1 to n in a single line:

n = 10  # Replace with your desired value of n
print(*range(1, n+1), sep=' ')

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading