Home » Learn Python » Conditions » Testing for Equality

Testing for Equality

Often we want to check if two things are equal to each other.

We can do this with the equality test operator, ==

Note that we do not use single ‘=’ to test if two things are equal; the single equals sign is called the assignment operator and is only used to assign values to variables.

value = 7
text = "hello"

print(value == 7)
print(value == 8)

print() # Create blank line

print(text == "hello")
print(text == "foxtrot")


Boolean Values

You can think of the == operator as like a function that accepts two arguments, which are the two things to be compared.

It returns either True or False.

The type of thing returned is actually bool, which is short for ‘boolean’. Boolean values can either be True or False.

print(type(1 == 2))
<class 'bool'>

What Can Be Compared?

As we’ll see later, lots of things can be compared using the equality test operator, but it’s probably most common to compare two integers, two boolean values, or two strings.

Often you’ll want to compare a variable with a literal value like 7 or “hello”.

  • You should not compare floating-point values with ==. This is unreliable because floating point values are not stored with infinite precision. Instead, use other operators or functions to check if two floating point values are close to each other.
  • String comparison is case-sensitive, so “Hello” is not equal to “hello”

Leave a Reply

Blog at WordPress.com.