3.7.1 An example of an if test

The if statement executes a nested code block if a condition is true. Here is an example:

      age = input("Please enter your age: ")
      if age > 40:
          print "Wow! You're really old!"

Copy this into an empty module and try to work out how if works. Make sure to include the colon and indent as in the example.

What Python sees is ``if the variable age is a number greater than 40 then print a suitable comment''. As in maths the symbol ``$>$'' means ``greater than''. The general structure of an if statement is:

      if [condition]:
          [statements to execute if condition is true]

      [rest of program]

Note: The text enclosed in square brackets it not meant to be typed. It merely represents some Python code.

Again indentation is important. In the above general form, the indented statements will only be executed if the condition is true but the rest of the program will be executed regardless. Its lack of indentation tells Python that it is nothing to do with the if test.