Ifs![[next]](../../img/ltp/arrow-next.gif)
We've previously seen if statements when checking to see the path to display different pages. Now let's look at the if statement in greater detail.
|
1
2 3 4 5 6 7 8 9 10 printp("How do I love thee? ", "Let me count the ways:") for (var x = 1 ; x < 10 ; x = x + 1) { if (x == 1) { printp(x, " way") } else { printp(x, " ways") } } |
Click to run the code. |
Each time through the loop in the example above, we check to see if x is 1, in which case we want to print "1 way" instead of the utterly less impressive "1 ways". (Does every website that says something silly like "1 messages" have a lazy programmer behind it that didn't bother to add an if statement? Yes.)
if statement.As the if statement's name implies: if the condition's value is true, then the block of code called the "true" block is evaluated. Otherwise, the "else" block code is evaluated. The else { ... } part is optional.
|
1
2 3 4 5 6 7 8 9 10 11 12 13 14 if (request.path == "/") { printp("Enter the password:"); print(form("/check", "password")); } if (request.path == "/check") { if (request.params.password == "s3kr1t") { printp("Excellent. The magic words are ", "\"squeamish ossifrage\""); } else { printp("Invalid password! ", "This incident will be reported."); } } |
Click to run the code. |
In the above example, we print a form to get a password from our user. Then we check the password and respond with some top secret codewords if the password is correct. (The magic words have some historical significance.)
Exercise: Multiple passwords. Change your code so that if the password is "s3kr1t" your app prints the secret code, but if the password is "f00b4r", your app prints a different secret code. Make sure to still print a message if the password is invalid.
Loops and conditionals are especially useful when you have lots of data you want to do something with, as we'll see in the next chapter.