How to Create a Loop in Python from 1 to n?

Estimated read time 1 min read

To create a loop in Python from 1 to n, where n is a positive integer, you can use either a for loop or a while loop. Here are examples of how to create such loops:

Example 1: Using a for loop

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

In this example, we use a for loop with the range() function to loop over the numbers 1 to n. The loop iterates n times, and for each iteration, the value of i is printed to the console.

Example 2: Using a while loop

n = 10
i = 1
while i <= n:
    print(i)
    i += 1

In this example, we define a variable i with an initial value of 1, and a variable n with the desired upper limit. We then use a while loop to loop until i is greater than n. For each iteration of the loop, we print the value of i to the console, and then increment i by 1 using the += operator.

You can modify these examples to perform different actions inside the loop, such as performing calculations or iterating over different ranges of numbers.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply