How to Use the if…else Statement in a Python Application

By John Paul Mueller

Even entering data of the wrong type produces an error message in Python, but entering the correct type of data outside the range tells the user nothing. In this example, you discover the means for correcting this problem by using an else clause. The following steps demonstrate just one reason to provide an alternative action when the condition for an if statement is false.

  1. Open a Python File window.

    You see an editor in which you can type the example code.

  2. Type the following code into the window — pressing Enter after each line:

    Value = int(input("Type a number between 1 and 10: "))
    if (Value > 0) and (Value <= 10):
     print("You typed: ", Value)
    else:
     print("The value you typed is incorrect!")

    The example obtains input from the user and then determines whether that input is in the correct range. However, in this case, the else clause provides an alternative output message when the user enters data outside the desired range.

    Notice that the else clause ends with a colon, just as the if statement does. Most clauses that you use with Python statements have a colon associated with them so that Python knows when the clause has ended. If you receive a coding error for your application, make sure that you check for the presence of the colon as needed.

  3. Choose Run→Run Module.

    You see a Python Shell window open with a prompt to type a number between 1 and 10.

  4. Type 5 and press Enter.

    The application determines that the number is in the right range.

  5. Repeat Steps 3 and 4, but type 22 instead of 5.

    image0.jpg

    This time the application outputs this error message. The user now knows that the input is outside the desired range and knows to try entering it again.