Selection > if - if/else - if/else if

What is it?

Selection let's your programs do one thing or another. Without selection your program couldn't react very well to different inputs. It would be stuck doing the same thing always. 

With the almighty powerful if statement your program becomes far more powerful!
Simply printing if someone is old enough to vote requires selection. There is no other way you can do it! 











 Python Java / Processing
 

if age >= 18:

  print "you can vote"

 
if (age >= 18) {

  println("you can vote");

}










 Python Java / Processing
 

if turn == "right":

  print "turn right here!"

else:

  print "turn left!"

 

if (turn == "right") {

 println("turn right here!");

} else {

  println("turn left!");

}













 Python Java / Processing
 

if grade == 10:

  print "welcome to ym!"

elif grade == 11:

  print "hey, still here?"

elif grade == 12:

  print "nearly out of here!"

 

if (grade == 10) {

  println("welcome to ym!");

} else if (grade == 11) {

  println("hey, still here?");

} else if (grade == 12) {

  println("nearly out of here!");

}






Example

The program flow changes if a condition is met - in this case if someone is 18 or older. If this is true a message is printed - if it is not true, ie. under 18 then no message is printed. 

See the examples below as well as: handout

Exercises: Python











Need to do something only if some condition is true? Perhaps you want your outside light on only at night time? Perhaps you want a program checks if someone is at least 18 and then prints out "You can vote!" You need to use the power of selection and the if statement!

In the code samples the the line directly after the if will print it's message only if the age of the user (they would have typed this in) is 18 or older.























The if statement is often used along with the else statement. The else statement gives you an alternative path of execution. If the condition is true your code will do one thing, if it is false it will do another.



























Other times your code needs to really filter out a bunch of different things. You can chain together many if statements using else if. If the first condition isn't true then execution moves on to another condition to test. You can use as many if elses as you need!

In Java/Processing the command is else if and in Python the keyword is elif
Ċ
James Cordiner,
Oct 11, 2013, 9:41 PM
Comments