Pulsars
0 %
Log inSign up

Conditions

Comparing and combining conditions

Comparing and combining conditions

To write a condition, you need comparison operators, which always return a boolean (True or False):

  • == equal to (careful, two equal signs, so as not to confuse it with the assignment =)
  • != different from
  • > strictly greater than
  • < strictly less than
  • >= greater than or equal to
  • <= less than or equal to
print(5 == 5)   # (displays True)
print(5 == 6)   # (displays False)
print(3 != 4)   # (displays True)

A very common mistake among beginners is writing if x = 5: instead of if x == 5:. The single = is used to assign a value, the double == is used to compare: they are not at all the same thing, and Python treats if x = 5: as a syntax error.

You can also combine several conditions using boolean operators:

  • and: true only if both conditions are true
  • or: true if at least one of the two conditions is true
  • not: negates a condition
age = 16
a_un_billet = True

if age >= 12 and a_un_billet:
    print("Entry allowed")
else:
    print("Entry denied")

Here, entry is allowed only if both conditions are true at the same time: being at least 12 years old, and having a ticket. If just one of the two is missing, and returns False, and the program displays Entry denied.

Choosing correctly between and, or and the comparison operators is essential so that your program makes exactly the decision you want.