Selection

Ifs allow us to make selections in programming and to decide which direction we go in a program. It’s rather like waking up in the morning and thinking “Mmm, if its sunny today I will go to the beach otherwise I’ll stay at home and polish my shoes.”   In this example or are taking an input (the weather) and checking it against something (Sunny)  if the two match and therefore your statement is true then you do one thing otherwise you’ll do something else (the false branch). We could write this in pseudo-code like this:

Basic Python IFs

This example tests the players score to see if it is a win, draw or lose. pythonIFs.png - 11/2015

Or we can test a number to see if its negative.

Note the first line is using our input function again but this time it is prefixed by a int function – this is important.  First, you need to be aware that because you have two open brackets you must have two close brackets in the right places!  Secondly, the int function serves to turn the value given by the user into a proper integer number.

A Little Challenge: rewrite this program for yourselves but change it so it tests for positive and add appropriate comments for each line so your teacher can assess your understanding.

Nested IFs

Sometimes we need to ask more than one question in which case we use something call nested IFs.  The following example (in pseudo code) tests for positive and negative numbers.

Now rather than using else if in Python we have to use the reserved keyword elif.

Another little challenge: try and rewrite the program above in proper Python code with comments.

About CDB 362 Articles
Self-Employed Software Developer, Spark, Property Management, Hobby Forestry, Ex-Teacher, Engineering - Wood, Metal, Electrics & Computers. Outdoors - Walk, Cycle, Kitesurf,

Be the first to comment

Leave a Reply

Your email address will not be published.


*


This site uses Akismet to reduce spam. Learn how your comment data is processed.