More Uses for Else in Python

Python's else statement is pretty versatile and can be used with more than just if conditionals. You can also use else with for and while loops, and also as part of a try / except block.

In the case of for loops, the else block executes if the main loop wasn't terminated by either a break statement, or an exception. For while loops, the else block runs when the loop condition evaluates to False at the start of a new iteration. If a break statement is encountered, or an exception occurs, the loop condition doesn't get checked again, so both of these cases prevent the else clause from running, just like with for loops.

In the the case of try / except, the else block runs in the event that an exception wasn't encountered as part of the try block.

# Print whether or a not an integer is prime for all integers from 2 to 100
for dividend in range(2,101):
    divisor = 2

    while dividend >= divisor ** 2:
        result = dividend / divisor
        if result.is_integer():
            print(f"{dividend} is not prime")
            # Break the while loop when a number is proven non-prime
			break
        divisor += 1

	# The else block runs if no break was encountered in the while loop
    else:
        print(f"{dividend} is prime")


"""
Convert the user input to an integer value and check the user's age is
over 18 if the conversion is successful. Otherwise, print an error message.
"""
try:
    age = int(input("Enter your age: "))
except:
    print ("Please only enter numerical characters.")

# The else block only runs if no exception gets raised
else:
    if age < 18:
        print("Sorry, you're too young to watch this movie.")
    else:
        print("Enjoy the movie!")

You can read more about using else statements with loops in the official docs.

Wrapping up

I hope you enjoyed the post, and that you learnt something new!

If you're really looking to upgrade your Python skills even further, you might want to try out our Complete Python Course, or join our Discord server! You should also think about signing up to our mailing list below, as you'll get regular discount codes for our courses, ensuring you always get a great deal.