Comparing values

The power of programming comes from letting the computer do work for us. To do that it needs to make decisions. Python will make decisions on the basis of comparing one value to another.

For instance, check to see what Python will print for the following statements:

print( 1 == 1 )
print( 1 == 0 )
print( "a" == "a" )
print( "a" == "A" )
print( "a" != "z" )
print( 1 > 0 )
print( -1 > 0 )
print( 2 >= 3 )
print( -3 < -1 )
print( 3 < 1 )
print( 2 <= 3 )

As a summary of the different symbols and what they mean:

Common mistake: Assignment or comparison?

Take careful note of the difference in punctuation between setting a value to a variable, and comparing two values! Setting a variable to a given value uses the single equal sign = whereas comparing two values or variables uses the double equal sign ==.

Using “in” and “not in”

We can also ask Python to check to see if one bit of text appears in another text string.

print( "h" in "hello" )
print( "z" in "hello" )
print( "z" not in "hello" )

Exercises

What would this do?

number_text = input("Type a number: ")
number = int(number_text)
print( "Is your number bigger than 10?" )
result = number > 10
print( result )

How is this one different?

number_text = input("Type a number: ")
number = int(number_text)
result = number > 10 and number < 100
print( result )

Here is an example checking to see if one string appears inside another:

secret = "abracadabra"
letter = input("Guess a letter: ")
print( "Is your letter inside the secret word? " )
answer = letter in secret
print( answer )