Kodeclik Logo

Our Programs

Courses

Learn More

Schedule

Kodeclik Blog

How to make a Python else statement do nothing

Sometimes we get asked the question:

Here's a practical example where you might need an empty else statement - a simple password validation system:

def validate_password(password):
    if len(password) < 8:
        print("Password is too short!")
        return False
    else:
        # WHAT DO WE WRITE HERE?

If you run this program, you will get:

  File "main.py", line 7
                                 ^
SyntaxError: unexpected EOF while parsing

We get a complaint that the else clause is empty. We can for instance, replace it with a useless statement, such as:

def validate_password(password):
    if len(password) < 8:
        print("Password is too short!")
        return False
    else:
        v = 2

Here we added “v=2” and we really don’t care about the variable v. We just added it to stop Python from complaining. But this is considered poor practice.

The other option is to use ellipsis (“...”), like so:

def validate_password(password):
    if len(password) < 8:
        print("Password is too short!")
        return False
    else:
        for i in range (1,100):
            ...

Here we have created a dummy for loop in the else: clause and inside the for loop we have added an ellipsis (“...”) statement. The ellipsis is an expression that represents a value. That value evaluates to True when converted to a boolean, but you should think of it as a constant and singleton object, similar to “None”. The for loop here merely creates additional delays by making the program run through this 100 times.

While ellipsis is an expression, what you really need is a statement that does nothing and that statement is the “pass” statement.

The “pass” statement

Here is how your code will look if we use the “pass” command.

How to make an else statement do nothing
def validate_password(password):
    if len(password) < 8:
        print("Password is too short!")
        return False
    else:
        pass

You will see that the above program compiles. The pass statement is a null operation that does nothing when executed - it's simply discarded during byte-compilation. It serves as a placeholder when Python's syntax requires a statement, but no code needs to be executed.

You might argue that we do not need an else clause here at all, like so:

def validate_password(password):
    if len(password) < 8:
        print("Password is too short!")
        return False

The problem with this code is that ideally you want your code to be exhaustive, i.e., it should have an answer or execution path for all inputs and in this case return something if your password satisfies the length requirements.

Another option is to use a “not” in your if statement:

   if not (len(password) < 8):
        # Continue with validation

This approach follows Python's "Flat is better than nested" philosophy and results in cleaner, more maintainable code. But in this case, it makes the logic less clear (and you have to wonder what should happen if we do not satisfy this condition - do you not want to inform the user with a friendly message about what went wrong?)

For all these reasons, it is good to use a “pass” statement.

Let us continue our program and write a more complete password validator.

A complete password validator

Here’s a more elaborate password checker:

def validate_password(password):
    print ("Validating " + password)
    if len(password) < 8:
        print("Password is too short!")
        return False
    else:
        pass  # Password length is okay, continue with the rest of the function
    
    # Continue checking other password requirements
    has_number = any(char.isdigit() for char in password)
    has_letter = any(char.isalpha() for char in password)
    
    if not (has_number and has_letter):
        print("Password must contain both letters and numbers!")
        return False
        
    return True

# Test the function
password1 = "abc123xyz"  # Valid password
password2 = "abc"        # Too short
password3 = "abcdefgh"   # No numbers

print(validate_password(password1))  
print()
print(validate_password(password2))  
print()
print(validate_password(password3)) 

The above password validation program consists of a function called validate_password that checks if a given password meets specific security criteria. When a password is passed to the function, it first verifies if the length is at least 8 characters - if not, it immediately returns False and displays an error message.

If the length check passes, the program continues (using else: pass) to examine two more requirements: the presence of at least one number and one letter in the password. It uses the any() function with isdigit() and isalpha() to check for numbers and letters respectively. If either requirement is missing, the function returns False with an appropriate error message.

The program includes three test cases: "abc123xyz" (which passes all checks), "abc" (which fails due to being too short), and "abcdefgh" (which fails because it lacks numbers). The function only returns True if the password satisfies all requirements - being at least 8 characters long and containing both letters and numbers.

If you run this program you get:

Validating abc123xyz
True

Validating abc
Password is too short!
False

Validating abcdefgh
Password must contain both letters and numbers!
False

Pass and other “null” operations in Python

The Python pass statement is unique among null operations due to its specific role and behavior in the language. It serves as an explicit placeholder when Python's syntax requires a statement in a code block. Unlike other languages that use curly braces to define empty blocks, Python specifically requires the pass keyword to create valid empty suites.

The pass statement is completely discarded during the byte-compilation phase, making it a true null operation with zero runtime impact. This differs from alternatives like comments or empty lines, which don't satisfy Python's syntactical requirements.

Comparison with Alternatives

Ellipsis (...)

As mentioned earlier, while ellipsis can serve as a placeholder, it's technically an object rather than a null operation. Unlike pass, ellipsis creates an actual object in memory.

Empty String Docstrings

Using docstrings ('''comments''') as placeholders isn't equivalent to pass because docstrings are treated as string literals and stored in memory.

Comments

Comments are ignored by the interpreter but cannot serve as syntactical placeholders in code blocks where statements are required.

I hope you learnt how its unique combination of features makes pass an interesting and essential part of Python's syntax, specifically designed for cases where code blocks must exist but should do nothing!

Enjoy this blogpost? Want to learn Python with us? Sign up for 1:1 or small group classes.

Kodeclik sidebar newsletter

Join our mailing list

Subscribe to get updates about our classes, camps, coupons, and more.

About

Kodeclik is an online coding academy for kids and teens to learn real world programming. Kids are introduced to coding in a fun and exciting way and are challeged to higher levels with engaging, high quality content.

Copyright @ Kodeclik 2024. All rights reserved.