In addition to speed and accuracy, one quality that makes computers powerful is their ability to evalu-
ate information and make small decisions quickly

if Statements

It asks if something is true, and based on the answer, it decides whether to perform a set of actions or skip over them. It allows us to tell the computer whether to run a group of instructions, based on a condition or set of conditions. With an if statement, we can tell the computer to make a choice.

Booleans

The condition we’re testing in an if statement is usually a Boolean expression, or a true/false test. A Boolean expression evaluates to either True or False.

Boolean expressions, or conditional expressions, are important programming tools: the computer’s ability to make decisions depends on its ability to evaluate Boolean expressions to True or False.

We have to use the computer’s language to tell it the condition we’d like to test.

Math symbol Python operator Meaning Example Result
< < Less than 1< 2 True
> > Greater than 1> 2 False
<= Less than or equal to 1 <= 2 True
>= Greater than or equal to 1 >= 2 False
= == Equal to 1 == 2 False
!= Not equal to 1 != 2 True

else Statements

Often we want our program to do one thing if a condition evaluates to True and something else if the condition evaluates to False. This is so common, in fact, that we have a shortcut, the else statement, that allows us to test if the condition is true without having to per- form another test to see if it’s false. The else statement can only be used after an if statement, not by itself, so we sometimes refer to the two together as an if-else.

elif Statements

There’s one more useful add-on to an if statement: the elif clause. An elif is a way to string together if-else statements when you need to check for more than two possible outcomes. The keyword elif is short for “else if.”

Summary

At this point you should be able to do the following:

  • Use if statements to make decisions using conditionals.
  • Use conditionals and Boolean expressions to control program flow.
  • Describe how a Boolean expression evaluates to True or False.
  • Write conditional expressions using comparison operators (<, >, ==, !=, <=, >=).
  • Use if-else statement combinations to choose between two alternative program paths.
  • Test a variable to see if it is odd or even using the modulo operator, %.
  • Write if-elif-else statements that select from among a number of options.
  • Use and and or to test multiple conditions at once.
  • Use the not operator to check whether a value or variable is False.
  • Explain how letters and other characters are stored as numeric values in computers.
  • Use ord() and chr() to convert characters into their ASCII equivalents and vice versa.
  • Manipulate strings using various string functions like lower(), upper(), and isupper().
  • Add strings and characters together using the + operator.

Challenges