The if statement is used to check a condition and if the condition is true, we process a block of statements (called the if-block), else we process another block of statements (called the else-block). The else clause is optional.
Example 6.1. Using the if statement
#!/usr/bin/python # Filename : if.py number = 23 guess = int(raw_input('Enter an integer : ')) if guess == number: print 'Congratulations, you guessed it.' # new block starts here print "(but you don't win any prizes!)" # new block ends here elif guess < number: print 'No, it is a little higher than that.' # another block # You can do whatever you want in a block ... else: print 'No, it is a little lower than that.' # you must have guess > number to reach here print 'Done' # This last statement is always executed, after the if statement # is executed.
$ python if.py Enter an integer : 50 No, it is a little lower than that. Done $ python if.py Enter an integer : 22 No, it is a little higher than that. Done $ python if.py Enter an integer : 23 Congratulations, you guessed it. (but you don't win any prizes!) Done
In this program, we take guesses from the user and check if it is the number that we have. We set the variable number to any integer we want, say 23. Then, we take the user's guess using the raw_input() function. Functions are just reusable pieces of programs.
We supply a string to the built-in raw_input function which then prints it to the screen and waits for input. Once we enter a number and press enter, then the function returns that input which, in the case of raw_string(), is always a string. We then convert this string to an integer using int and then store it in the variable guess. Actually, the int is a class but all you need to know right now is that you can use it to convert a string to an integer.
Then, we compare the guess of the user with the number we have. If they are equal, we print a success message. Notice that we use indentation levels to tell Python which statements belong to which block. This is why indentation is so important in Python. I hope you are sticking to 'one tab per indentation level' rule.
Notice how the if statement contains a colon at the end - we are indicating to Python that a block of statements follows.
Then, we check if the guess is less than the number, and if so, we inform the user to guess a little higher than that. What we have used here is the elif clause which actually combines two related if else-if else statements into one combined if-elif-else statement. This makes the program more readable and clearer. It also reduces the amount of indentation required.
The elif and else statements must also have a colon at the end of the logical line followed by their corresponding block of statements (with higher level of indentation, of course).
You can have another if statement inside the if-block of an if statement - this is called a nested if statement.
Remember that the elif and else parts are optional. A minimal valid if statement is
if True: print 'Yes, it is true'
After Python has finished executing the complete if statement along with the associated elif and else clauses, it moves on to the next statement in the block containing the if statement. In this case, it is the main block where execution of your program starts and Python moves on to the print 'Done' statement, then sees the end of the program and quits.
Although this is a very simple program, I have been pointing out a lot of things that you should notice even in this simple program. All these are pretty straightforward (and surprisingly simple for those of you from C/C++ backgrounds) and requires you to become aware of them initially but after that, you will become comfortable with it.
We will now see an equivalent program of the above in C to help newbies to understand how easy Python is compared to a language like C, and to help experienced programmers grasp the differences between the C/C++ family of languages and Python.
You can skip this section if you want to.
Note that indentation does not matter in C. One of the reasons why C programs are (usually) more difficult to understand is that it may not be written clearly. However, a good programmer always has a good and consistent indentation style. When it comes to Python, the programs always have to be written clearly!
Example 6.2. Equivalent C Program
#include <stdio.h> /* Filename: if.c */ /* Execution of a C program always start from the main() function */ int main() { /* declare variables before using them, we also have to specify the data type of the variables. */ int number, guess; /* the number we have to guess */ number = 23; /* input the guess of the user */ printf("Enter an integer : "); scanf("%d", &guess); if (guess == number) /* expression within parentheses */ { /* block enclosed within parentheses */ printf("Congratulations, you guessed it.\n"); printf("(but you don't win any prizes!)\n"); } else if (guess < number) { printf("No, it is a little higher than that.\n"); } else { /* you must have guess > number to reach here */ printf("No, it is a little lower than that.\n"); } printf("Done.\n"); return 0; /* return an exit value to the shell */ }
There is no switch statement in Python. You can use an if..elif..else statement to do the same thing.