Sunday, June 5, 2011

This way or that way

Sometimes you need the computer to make a decision. You don't want it to do the exact same thing every time. How do we tell the computer to do one thing or another if something happens? If is the answer, and else. Look at this example:
We have a secret number in the variable secret, then we ask for a guess and put it in a variable we call guess. Next, we compare our guess with the secret number. But guess isn't a number yet, so we make it one using int(). Then we use the equal-sign twice to compare guess and secret.

Wait, we use the equal sign twice?

Yep, the equal sign was used before to assign the number 5 to our variable secret. Then we use two equal signs to compare the variables secret and guess.

Why are there spaces in front of print? Because we need to tell the computer that the print happens under the if statement, instead of happening all the time. If we wanted to print more things or do other things if we guessed the correct number, then we could line up the next command under print. We call this print statement indented when it has spaces before it.

But it would be better if the computer told us if we got our guess wrong. That's where else comes in:
Else happens when the if comparison is false. See that there are no spaces before else. This is because it doesn't happen when we guess the number, but when we don't. The print statement here is also indented.

No comments:

Post a Comment