Skip to main content

Chapter 4a - Boolean

Introducing Boolean Expression​

πŸ‘€

Boolean ExpressionAithmetic Expression
2 > 32+3
Comparison OperatorDefinitionExample
==Equals2==2 -> True, 2==4 -> False
!=Not Equal2!=3 -> True, 2!=2 -> False
>Larger3>2 -> True
<Smaller4 < 5 -> True
>=Larger or Equals4 >= 2 -> True, 2>=2 -> Tru

Practice

Complete the following using the correct Boolean Expressions:

  • Note we are using ages now.
  • In Line 8 you can see how inside of str() we have the Boolean Expression for answering the statement Tom is of the same age as Marie
  • Complete with the appropriate Boolean expressions in line 12, 13, 14

πŸ™‹β€β™€οΈ Correct Output

py-l4b-print-x

Tom is of the same age as Marie: False
Tom is older than Marie: True
Marie is younger than Alisha: True
Joe is as old as Tom: True

Logical Operators​

πŸ‘€

Practice

Complete the following code with appropriate logical expressions


πŸ™‹β€β™€οΈ Correct Output

x-py-l4c-booleanexpressions

Tom is older than Marie and Darell: True
Tom is older than Darell and Alisha: True
Marie is younger than Darell and Alisha: True

Integrated Exercise​

Hard: Fair Ride​

Fair Ride

` Fair Ride: Create a boolean expression that will be true or false for the given situation.

The situation is this: You’d like to go on a ride at the fair, but you have to meet the following criteria. You must be over 5 feet tall or have your parent with you to go on the ride. You may use the following variables -

height - int

hasParent - boolean

canRide - boolean

i) Accept user input for height and hasParent. To accept a boolean value from the user, typecast the user’s input to bool(). User needs to write something => true or nothing => false.

ii) Use comparison operator to write a boolean expression that will evaluate to True or False depending on whether or not height is more than 5 feet. Output the value of the boolean expression.

iii) Use logical operator to combine hasParent and the boolean expression from (ii) to construct a complex boolean expression and save the result in canRide. canRide evaluates to True if either hasParent or the boolean expression from (ii) is True. Output the value of canRide.


πŸ™‹β€β™€οΈ Sample Program