鶹Լ

Using Boolean logic in programming

is used in to test conditions.

Consider this simple Python (3.x) that prints out a different message depending on how old you are:

age = int(input("How old are you?"))
if age >= 70:
	print("You are aged to perfection!")
else:
	print("You are a spring chicken!")

This program uses selection to determine whether to print one message or the other:

  • The program examines the of the Boolean in line 2.
  • If the inputted age is greater than or equal to 70, then the condition is True. As a result the program prints “You are aged to perfection!”
  • If the inputted age is less than 70, then the condition is False. As a result, the program prints “You are a spring chicken!”

Building up complex decisions with Boolean expressions

The following Python (3.x) program works as above but has the added feature of checking to see if the inputted age is 50:

age = int(input("How old are you?"))
if age >= 70:
	print("You are aged to perfection!")
elif age == 50:
	print("Wow, you are half a century old!")
else:
	print("You are a spring chicken!")

As well as checking the condition of the Boolean expression in line 2, this program also checks the condition of the Boolean expression in line 4:

  • The program examines the condition of the Boolean expression in line 2.
  • If the age that is input is greater than or equal to 70, then the condition is True. As a result the program prints “You are aged to perfection!”
  • If the age that is input is less than 70, then the condition is False. The program then examines the condition of the expression in line 4.
  • If the age that is input is equal to 50, then the first condition (age >= 70) is False, but the second condition (age == 50) is True. As a result the program prints “Wow, you are half a century old!”)
  • If the age that is input is not greater than or equal to 70 and not equal to 50, then both expressions are False. As a result the program prints “You are a spring chicken!”

Boolean logic does not just work with numbers. Boolean expressions can also compare text, for example to check if a password is correct.

Consider this Python (3.x) program, which repeats if a password has been entered incorrectly:

answer = ""
while answer != "ilovecomputing":
	answer = input("Type in the password: ")
print("Password correct”)

This program uses selection to determine whether to repeat, but this time compares text, not numbers.

  • The program examines the condition of the Boolean expression in line 2. It is looking to see if the value of ‘answer’ does not equal “ilovecomputing”
  • If the value of ‘answer’ does not equal “ilovecomputing”, then the condition is True. As a result the program asks the user to input the password and repeats the comparison.
  • If the value of ‘answer’ equals “ilovecomputing” then the condition is False. As a result, the program skips the loop and proceeds to the last line of the program, which prints “Password correct”.