An Introduction to Python For Undergraduate Engineers/If/Else

Now that you have a few of the basic components under your belt, it is now the time to make some extra tools available to you. The most important part of a program is often the ability to get your program to do something if something is true (or false). For example if an inputted value is above a set value. For example:

This little program will ask the user to input their age and then test whether it is greater than or equal to 18. If the user is old enough, a message saying continue is printed on screen, otherwise the user is told to go away!

The if statement will run a logical test and then run the commands after it if the test result is true. If the result is false, it will run the commands after the else: statement. If there is no else statement and the result is false, the program will do nothing.

You can add further tests before the else commands are run using the elif statement (stands for else if). It will act like another if statement after the first one until if all if test are false, then and only then will the else commands be run. For example: