Learn more

Chapter 7: If Statements


The final core programming control-flow construct to learn are conditional statements (if and if/else).

Basic Conditionals

An if/else statement executes an "if" code-block if and only if the provided test is true for the state of the world at the time the program reaches the statement. Otherwise the program executes the "else" code-block.

if test:
if code-block
else:
else code-block

To get a sense of where conditional statements might come in handy, let's write a program that has Karel invert a line of beepers. If a square previously had a beeper, Karel should pick it up. If a square has no beeper, Karel should put one down.

Note that an if statement does not need to have an else block -- in which case the statement opperates like a while loop that only executes one time:

if test:
if code-block

Conditions

That last example used a new condition. Here is a list of all of the conditions that Karel knows of:

TestOppositeWhat it checks
frontIsClear() frontIsBlocked() Is there a wall in front of Karel?
beepersPresent() noBeepersPresent() Are there beepers on this corner?
leftIsClear() leftIsBlocked() Is there a wall to Karel’s left?
rightIsClear() rightIsBlocked() Is there a wall to Karel’s right?
beepersInBag() noBeepersInBag() Any there beepers in Karel’s bag?
facingNorth() notFacingNorth() Is Karel facing north?
facingSouth() notFacingSouth() Is Karel facing south?
facingEast() notFacingEast() Is Karel facing east?
facingWest() notFacingWest() Is Karel facing west?

Putting it all together

Congrats! You now know all of the core programming control-flow blocks. While you learned them with Karel, methods, while loops, for loops, if/else statements work in the same way in almost all major languages, including Java.

Now that you have the building blocks you can put them together to build solutions to ever more complex problems. To a large extent, programming is the science of solving problems by computer. Because problems are often difficult, solutions—and the programs that implement those solutions—can be difficult as well. In order to make it easier for you to develop those solutions, you need to adopt a methodology and discipline that reduces the level of that complexity to a manageable scale.


Next Chapter