Read an Answer and Compare It

A program that asks a question has three small jobs: read what the person types, tidy that text so small differences in typing do not matter, and compare it with the answer it expects. Python has one tool for each job, and each one gives back a value you can look at, store in a variable and print, so you can predict what the program will decide before you run it.

Reading a line with input

So far a program has only shown things on the screen with print. To let a person answer, Python has a built-in function called input. A function is a named piece of ready-made code, and you call it by writing its name followed by parentheses, just as you call print.

A call to input does three things, in this order:

  • Show the prompt no line break after it
  • Wait for a line until Enter is pressed
  • Give the line back always as a string
  • Show the prompt to Wait for a line
  • Wait for a line to Give the line back

The text between the parentheses is the prompt: the question shown to the person. Python writes it without moving to a new line, so whatever the person types appears right after it. That is why a prompt usually ends with a space or with ? , to leave a gap before the typing.

Then the program stops and waits. Nothing below the input line runs while the person is typing. The line is finished only when they press Enter. At that moment input hands the line back, without the Enter itself, and the program carries on. The usual way to keep that line is to assign it to a variable:

city = input("Capital of France? ")
print(f"You typed: {city}")
Running it, and typing Paris
Capital of France? Paris
You typed: Paris

Whatever the person types comes back as a string, a piece of text, even when it is made of digits. If someone types 4, the variable holds the text "4", not the number 4. A program that needs a number converts the string, for example with int(...).

input also keeps every other key the person pressed. If they type two spaces before Paris, or write it as PARIS, the string holds exactly that: " PARIS". Only the Enter at the end is dropped.

True or false?

When the user types 42 at an input prompt, input gives back the whole number 42.

False. input always gives back a string. The result is the text "42", which has to be converted with int() before it can be used as a number.

While the program waits at input, the lines below it have not run yet.

True. The program pauses on the input call until a line is finished with Enter, then continues with the next line.

If the user types a space before their answer, input removes it.

False. input removes only the Enter at the end of the line. Spaces and capital letters stay exactly as they were typed.

Tidying text with string methods

Because the typed line keeps its stray spaces and its capital letters, a program usually tidies it before using it. Strings come with their own functions for this, called methods. A method is a function that belongs to a value. You call it by writing the value, a dot, the method's name and parentheses: city.strip() means "call the strip method of the string in city".

Two methods cover most tidying:

  • strip() gives back the text without the spaces at the start and at the end. It also removes tabs and line breaks there. Spaces between words stay.
  • lower() gives back the text with every capital letter turned into a small one. Its partner upper() does the opposite.
ExpressionGives back
" Paris ".strip()"Paris"
" New York ".strip()"New York"
"PaRiS".lower()"paris"
"paris".upper()"PARIS"

The word that matters in both descriptions is gives back. A string in Python can never be changed once it exists. So strip() does not clean the string it was called on: it builds a new, tidied copy and hands that copy back. If nothing keeps the copy, it is lost, and the variable still holds the original text. To keep the tidy version, assign it, often to the same name:

city = "  Paris "
city.strip()          # makes a tidy copy, but nothing keeps it
print(f"[{city}]")    # [  Paris ]

city = city.strip()   # the name now refers to the tidy copy
print(f"[{city}]")    # [Paris]

The square brackets in the f-string are only there to make the spaces visible on the screen.

Since each of these methods gives back a string, you can call the next method straight on that result. This is called chaining, and Python runs the calls from left to right:

  • " PARIS " what input gave back
  • "PARIS" a new string
  • "paris" another new string
  • " PARIS " to "PARIS": .strip()
  • "PARIS" to "paris": .lower()
city = input("Capital of France? ").strip().lower()

Here input gives back the raw line, .strip() is called on it, and .lower() is called on the stripped copy. The variable receives only the last result. The parentheses are part of every call: city.strip without them only names the method and does not run it.

True or false?

After the line word.lower() runs on its own, the variable word holds the text in small letters.

False. lower() gives back a new string and leaves the original unchanged. Only word = word.lower() makes the name refer to the small-letter copy.

" ice cream ".strip() gives back "ice cream", with two spaces in the middle.

True. strip() removes spaces only at the two ends. The spaces between the words are kept as they were.

In text.strip().lower(), lower() is called on the result of strip().

True. Chained calls run from left to right, and each method is called on the string the one before it gave back.

Asking whether two values are equal

Once the answer is tidy, the program has to ask a question about it: is it the same as the expected answer? In Python you ask with ==, two equals signs written together. Its opposite is !=, which asks whether two values are not equal.

A comparison is worked out like a calculation, and it has a result. That result is not a number or a string but one of two special values: True or False.

print(2 + 2 == 4)          # True
print("paris" == "paris")  # True
print("paris" != "rome")   # True
print("Paris" == "paris")  # False

Python compares strings exactly, letter by letter. A capital P and a small p are different letters to it, and a space is a letter like any other. That is the reason tidying comes first: the same answer typed in different ways only compares equal after both sides are in the same form.

ComparisonResultWhy
"Paris" == "paris"FalseP and p are different letters
" paris" == "paris"Falsethe first string starts with a space
" Paris".strip().lower() == "paris"Trueboth sides are now the same text
"3" == 3Falsea string never equals a number
3 == 3.0Truenumbers compare by their value

The fourth row matters for answers that are numbers. A string is never equal to a number, so the string "3" that input gives back is not equal to the number 3. Python does not stop with an error here. It simply answers False, which is easy to miss. To get the comparison you meant, either compare with the string "3", or convert the answer with int() first.

The last row shows that numbers behave differently. Whole numbers and decimal numbers are different types, but Python compares them by the amount they stand for, so 3 == 3.0 is True.

True or false?

If the user types 7 and the program checks input() == 7, the result is True.

False. input() gives back the string "7". A string is never equal to a number, so the comparison is False.

"yes" == "yes " is False.

True. The second string ends with a space, and == compares every character, spaces included.

Comparing for order

Besides equality, Python can ask which of two values comes first. These four comparisons also give True or False:

WrittenAsksExampleResult
<less than3 < 5True
>greater than3 > 5False
<=less than or equal to5 <= 5True
>=greater than or equal to4.5 >= 5False

The sign with the equals in it includes the equal case: 5 < 5 is False, but 5 <= 5 is True. The equals sign is always written second: <=, never =<.

Strings can be put in order too, and here Python follows a rule that surprises most people: it does not simply use alphabetical order. Every character, whether a letter, a digit or a space, has a number of its own in a standard table called Unicode. Python compares two strings by those numbers. It looks at the first character of each string; if they are the same, it moves on to the second, and so on, until two characters differ. The string whose character has the smaller number comes first.

For plain English letters and digits this rule has three consequences:

  • Small letters follow the alphabet, so "apple" < "banana" is True.
  • Every capital letter comes before every small letter, so "Zebra" < "apple" is True.
  • Digits in a string are characters, not amounts, so "10" < "9" is True: the first characters already differ, and "1" comes before "9".

Ordering a string against a number is not possible at all. "3" < 3 stops the program with a TypeError, an error saying that < is not supported between a string and a number. Equality is the gentle one of the two: "3" == 3 just gives False.

True or false?

"Zebra" < "apple" is True.

True. Strings are ordered by the numbers of their characters, and every capital letter has a smaller number than every small letter.

"10" < "9" is False, because 10 is bigger than 9.

False. These are strings, so Python compares characters, not amounts. "1" comes before "9", so the result is True.

Comparing "3" < 3 gives False.

False. Python cannot order a string against a number, so the program stops with a TypeError. Only == and != give an answer for such a pair.

True and False are values

True and False are not words that print happens to show. They are values of their own type, called bool (short for boolean), and that type has exactly these two values. They are written with a capital first letter and without quotes. With quotes, "True" is just a string of four letters, and a string is never equal to a boolean.

Like any value, the result of a comparison can be stored in a variable and used later:

answer = "  Paris".strip().lower()
correct = answer == "paris"

print(correct)         # True
print(type(correct))   # <class 'bool'>

Storing the result under a name such as correct makes the program easy to read: the question is asked once, and the name says what the answer means. Later, the program can make a decision from that one value.

True or false?

True and "True" are the same value.

False. True is a bool and "True" is a string. A string never compares equal to a boolean, so True == "True" is False.

The line same = 4 == 4.0 stores True in the variable same.

True. Python works out the comparison first, 4 == 4.0 is True, and then the single = assigns that value to the name same.

One equals sign or two

In everyday maths, one equals sign states that two things are equal. In Python the two jobs are split between two different signs, and mixing them up is one of the most common first mistakes.

The line correct = answer == "paris" from the section above uses both signs, and reading it in the right order makes the difference clear. Python first works out the right side, the comparison answer == "paris", which gives a boolean. Then the single = stores that boolean under the name correct.

Writing a single = where a comparison belongs does not compare anything, and what happens next depends on where it is written. Inside print, the line print("paris" = "paris") does not run at all: Python stops with a SyntaxError and the hint perhaps you meant "=="?. But correct = answer = "paris" runs without any error. It stores "paris" in both names, so correct holds a string instead of True or False, and the program carries on with the wrong value. When Python asks whether you meant ==, or a comparison seems to give text instead of a boolean, count the equals signs.

True or false?

After x = 5, the line x == 6 changes x to 6.

False. == only compares. It gives False here and leaves x holding 5. Only a single = changes what a name refers to.

In the line ok = guess == "blue", the comparison is worked out before anything is stored in ok.

True. Python evaluates the right side of an assignment first, so guess == "blue" becomes True or False, and that value is assigned to ok.