Range in Python

Why is the result *** ?
I thought it will only show ** since values are 1,2
Do we need to consider else clause as well?


for i in range (1,3):
    print("*", end="")

Yes. The loop did not encounter a break (or another abnormal exit that could skip the else:, such as return or raising an exception), so that clause will run:

(To verify this, you could have tried using a debugger, or by adding a completely different print inside the else: so that it’s clear which print is running each time.)

When it runs, i will be equal to the last value that was used inside the loop:

>>> for i in range(1, 3):
...     print(i, end='')
... else:
...     print(i)
1 Like

A for or while loop can include an else clause.
In a for loop, the else clause is executed after the loop reaches its final iteration.
In a while loop, it’s executed after the loop’s condition becomes false.
In either kind of loop, the else clause is not executed if the loop was terminated by a break.


thank you for the explanation!

thank you!

how to write a loop code when you are given various number and you need to find the highest

Hey @Jesh and welcome.

I’m sure that you’ll have your question answered, but you’ll need to provide an example of what you’re trying to do, rather than being vague about the details. Also, post up some code, so that we can see what you’re tried, and from which we’ll be able to tell you where you’ve gone wrong.

To add: it’s better to create a new thread for this, as you’ve a ‘question’ here, not a solution or advice for the OP of this thread.

1 Like