Jump to content

An Introduction to Python For Undergraduate Engineers/If/Else

From Wikibooks, open books for an open world

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:

   yourage = input("Please enter your age: ")
   if yourage >= 18: 
       print("You may continue...")
   else:
       print("You are too young..... go away!")

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:

   yourage = input("Enter your age: ")
   if yourage >= 80:
      print("Hello gramps!")
   elif yourage >= 60:
      print("You can get your free bus pass now!")
   elif yourage >= 40:
      print("Mid-life crisis due")
   elif yourage >= 18:
      print("Make the most of those looks whilst you still can!")
   else:
      print("Go back to school!")

If you are not quite sure what's going on try putting this into a script and running it in IDLE. See what message you get!