counter = 1
while (counter <= 5):
if counter < 2:
print("Less than 2")
elif counter > 4:
print("Greater than 4")
counter += 1
This will do what you want (if less than 2, print this etc.)
Answer from trolley813 on Stack Overflowcounter = 1
while (counter <= 5):
if counter < 2:
print("Less than 2")
elif counter > 4:
print("Greater than 4")
counter += 1
This will do what you want (if less than 2, print this etc.)
I'm assuming you want to say Less than 2 or Greater than 4 while incrementing from 1 to 4:
counter = 1
while (counter < 5):
if counter < 2:
print('Less than 2')
elif counter > 4:
print('Greater than 4')
else:
print('Something else') # You can use 'pass' if you don't want to print anything here
counter += 1
The program will never display Greater than 4 because your while condition is counter < 5.
While loops can have an else statement!
syntax - Else clause on Python while statement - Stack Overflow
if statement - Why does python use 'else' after for and while loops? - Stack Overflow
Whats the difference between a while loop and a for loop?
Videos
Maybe I'm the only one who didn't know this, but you can put an else statement after a while loop which will be used if the while loop is never entered. I found this out on the Leetcode problem of the day for today when I tried putting an else after my while loop, mostly expecting an error but typing because it's what I wanted the code to do, and it ran! The code I used is below. I know there are more optimal solutions, but I'm happy with what I learned today.
class Solution:
def dailyTemperatures(self, temperatures: List[int]) -> List[int]:
n = len(temperatures)
answers = [0] * n
stack = []
for i in range(n):
while len(stack) > 0 and temperatures[i] > stack[-1][1]:
answers[stack[-1][0]] = i - stack[-1][0]
stack.pop()
else:
stack.append([i, temperatures[i]])
if len(stack) == 0:
stack.append([i, temperatures[i]])
return answers
The else clause is only executed after the while condition is evaluated to be false.
Thus, if you break out of the loop, or if an exception is raised, the else won't be executed (since the while condition has not been evaluated to be false yet).
One way to think about it is as an if/else construct with respect to the condition:
if condition:
handle_true()
else:
handle_false()
is analogous to the looping construct:
while condition:
handle_true()
else:
# condition is false now, handle and go on with the rest of the program
handle_false()
An example might be along the lines of:
while value < threshold:
if not process_acceptable_value(value):
# something went wrong, exit the loop; don't pass go, don't collect 200
break
value = update(value)
else:
# value >= threshold; pass go, collect 200
handle_threshold_reached()
The else clause is executed if you exit a block normally, by hitting the loop condition or falling off the bottom of a try block. It is not executed if you break or return out of a block, or raise an exception. It works for not only while and for loops, but also try blocks.
You typically find it in places where normally you would exit a loop early, and running off the end of the loop is an unexpected/unusual occasion. For example, if you're looping through a list looking for a value:
for value in values:
if value == 5:
print "Found it!"
break
else:
print "Nowhere to be found. :-("
A common construct is to run a loop until something is found and then to break out of the loop. The problem is that if I break out of the loop or the loop ends I need to determine which case happened. One method is to create a flag or store variable that will let me do a second test to see how the loop was exited.
For example assume that I need to search through a list and process each item until a flag item is found and then stop processing. If the flag item is missing then an exception needs to be raised.
Using the Python for...else construct you have
for i in mylist:
if i == theflag:
break
process(i)
else:
raise ValueError("List argument missing terminal flag.")
Compare this to a method that does not use this syntactic sugar:
flagfound = False
for i in mylist:
if i == theflag:
flagfound = True
break
process(i)
if not flagfound:
raise ValueError("List argument missing terminal flag.")
In the first case the raise is bound tightly to the for loop it works with. In the second the binding is not as strong and errors may be introduced during maintenance.
It's a strange construct even to seasoned Python coders. When used in conjunction with for-loops it basically means "find some item in the iterable, else if none was found do ...". As in:
found_obj = None
for obj in objects:
if obj.key == search_key:
found_obj = obj
break
else:
print('No object found.')
But anytime you see this construct, a better alternative is to either encapsulate the search in a function:
def find_obj(search_key):
for obj in objects:
if obj.key == search_key:
return obj
Or use a list comprehension:
matching_objs = [o for o in objects if o.key == search_key]
if matching_objs:
print('Found {}'.format(matching_objs[0]))
else:
print('No object found.')
It is not semantically equivalent to the other two versions, but works good enough in non-performance critical code where it doesn't matter whether you iterate the whole list or not. Others may disagree, but I personally would avoid ever using the for-else or while-else blocks in production code.
See also [Python-ideas] Summary of for...else threads