How do I use if/elif/else condition in python?



  • The if, elif, and else provides a way of performing an action based on whether a condition is true or flase.

    The code below shows an example where if, elif, else is used.

    # if, elif, else conditions.
    
    username = "operator"
    if len(username) < 5:
        print("Username must be at least 5 characters.")
    elif len(username) > 15:
        print("Username cannot be greater than 15 characters.")
    else: 
        print("Nice Username!")
    

    As the value of username is less than 5 the result is:

    $ python main.py
    Username must be at least 5 characters.
    

    If we change the username variable to operator, greater than 5 the result would be:

    $ python main.py
    Nice Username!
    

    If we set the username to a value greater than 15. You would see.

    $ python main.py
    Username cannot be greater than 15 characters.
    

Log in to reply
 

© Lightnetics 2024