How to Create an If Statement in Python

The ability to use "if-then-else" logic in your program is one of the most basic and fundamental aspects to programming in any language. Python provides an easy and elegant way to tell your program what to do if something is true, and what to do if something is false.

Instructions

  1. Create an If Statement in Python

    • 1

      Determine which conditions you wish to test. A condition is simply a true or false statement that you can use for the control flow of your Python program. In our example case, we will create a bank account integer variable and check its limits:
      myBankInt = 50

    • 2

      Determine what events you want to occur if the if statement is true.

    • 3

      Create an if statement using your test condition, and place the events that occur if the statement is true immediately after the if statement. Use a colon (:) to indicate the end of the if statement:
      if myBankInt < 10:
          print 'My bank statement is less than 10'

    • 4

      Determine if you have more than one condition you wish to test off.

    • 5

      Know that if you have more than one condition, you can use else-if logic to continue your if statement. In Python, the keyword "elif" is used as shorthand for "else if". The elif statement ends with a colon (:)
      elif myBankInt < 20:
          print 'My bank statement is less than 20'

    • 6

      Use as many elif statements, one after another, as you need to satisfy your "else if" logic needs.

    • 7

      Determine the sequence of events you wish to occur if your if and elif statements are all false.

    • 8

      Plan ahead. If you have an "all else fails" scenario, use the else statement to conclude your if statement. The else statement ends with a colon (:)
      else:
          print 'My bank account is over 20'

Tips & Warnings

  • You can use standard boolean operators inside your if statement. Python uses the keyterms "and," "or" and "not" for these purposes. You can also use the boolean test operator "==" to see if something is equal to something else, but not assign the value.

  • In Python, control flow of a program is determined by mandatory indentation. After each if, elif or else statement you must use tab to indicate that you are within the "block" of your if statement. If you wish to nest if statements, be sure to indent even further.

Related Searches:

Resources

Comments

You May Also Like

Related Ads

Featured