Quarry School

Ask a true-or-false question — quick review

In plain words

A fairground ride has a height bar at its gate.

Rule

A comparison has a value on each side of a comparison operator. When both sides are numbers, or both are strings, Python works out the two sides, asks the question and gives back True or False. <, <=, > and >= ask about order. == asks whether the two values are equal, and != asks whether they differ.

Two whole numbers are equal when they are the same number. Two strings are equal when they hold the same characters in the same order, so "Gate" == "gate" is False. A string and a whole number are never equal, so "6" == 6 is False. Asking about order between a string and a number, as in "6" < 7, stops the program with a TypeError.

Step

  1. Say the question in words. For the boat program below, one question is whether the number of riders is more than the number of seats.

  2. Choose the operator that matches the words. "More than" is >. "At least" is >=. "Fewer than" is <. "At most" is <=. "Exactly" is ==. "Anything but" is !=.

  3. Check the types. A string and a whole number are never equal, so compare a number with a number and text with text. A value that came from input() is text. When that text is a whole number such as 6, int makes a number from it, as the second worked example shows.

  4. Work out each side to one value. Do any arithmetic first.

  5. Ask the question about those two values and write True or False.

Trap

The usual slip is typing = where you mean ==. In the Shell, riders = 6 gives the name a value and shows nothing. riders == 6 asks the question and shows True or False. When a comparison shows nothing, count the equals signs.

A quieter slip is comparing text with a number. "6" == 6 is False, and Python raises no error to warn you. If the value came from input() and holds a whole number, make a number from it with int before you compare it with a number.

The two-character operators have one spelling each. Write >=, <= and != with the = second. => and =< are not Python operators. A file that holds one stops with a SyntaxError before its first line runs.