Arithmetic, Logical & Boolean Operators (Cambridge (CIE) O Level Computer Science)

Revision Note

Robert Hampton

Written by: Robert Hampton

Reviewed by: James Woodhouse

What is an operator?

  • An operator is a symbol used to instruct a computer to perform a specific operation on one or more values

  • Examples of common operators include:

    • Arithmetic

    • Logical

    • Boolean

Arithmetic Operators

Operator

Pseudocode

Python

Addition

+

+

Subtraction

-

-

Multiplication

*

*

Division

/

/

Modulus (remainder after division)

MOD

%

Quotient (whole number division)

DIV

//

Exponentiation (to the power of)

^

**

  • To demonstrate the use of common arithmetic operators, three sample programs written in Python are given below

  • Comments have been included to help understand how the arithmetic operators are being used

    • Arithmetic operators #1 - a simple program to calculate if a user entered number is odd or even

    • Arithmetic operators #2 - a simple program to calculate the area of a circle from a user inputted radius

    • Arithmetic operators #3 - a simple program that generates 5 maths questions based on user inputs and gives a score of how many were correctly answered at the end

Python code

# -----------------------------------------------------------------------
# Arithmetic operators #1
# -----------------------------------------------------------------------
# Get the user to input a number
user_input = int(input("Enter a number: "))

# If the remainder of the number divided by 2 is 0, the number is even
if user_input % 2 == 0:
    print("The number is even.")
else:
    print("The number is odd.")


# -----------------------------------------------------------------------
# Arithmetic operators #2
# -----------------------------------------------------------------------
# Get the radius from the user
radius = float(input("Enter the radius of the circle: "))

# Calculate the area of the circle
area = 3.14159 * radius ** 2

# Display the calculated area
print("The area of the circle with radius", radius, "is", area)


# ------------------------------------------------------------------------
# Arithmetic operators #3
# ------------------------------------------------------------------------
# Set the score to 0
score = 0

# Loop 5 times
for x in range(5):
    num1 = int(input("Enter the first number: "))
    operator = input("Enter the operator (+, -, *): ")
    num2 = int(input("Enter the second number: "))
    user_answer = int(input("What is " + str(num1) + " " + str(operator) + " " + str(num2) + "? "))

    # Check the answer and update the score
    if operator == '+':
        correct_answer = num1 + num2
    elif operator == '-':
        correct_answer = num1 - num2
    elif operator == '*':
        correct_answer = num1 * num2
    else:
        print("Invalid operator!")
        continue

    if user_answer == correct_answer:
        score = score + 1
    else:
        print("Sorry, that's incorrect.")

# Display the final score
print("Your score is:", score)

Logical Operators

Operator

Pseudocode

Python

Equal to

==

==

Not equal to

<>

!=

Less than

<

<

Less than or equal to

<=

<=

Greater than

>

>

Greater than or equal to

>=

>=

Boolean Operators

  • A Boolean operators is a logical operator that can be used to compare two or more values and return a Boolean value (True or False) based on the comparison

  • There are 3 main Boolean values:

    • AND: Returns True if both conditions are True

    • OR: Returns True if one or both conditions are True

    • NOT: Returns the opposite of the condition (True if False, False if True)

  • To demonstrate the use of common Boolean operators, three sample programs written in Python are given below

  • Comments have been included to help understand how the Boolean operators are being used

    • Common Boolean operators #1 - a simple program that assigns Boolean values to two variables and outputs basic comparisons

    • Common Boolean operators #2 - a simple program to output a grade based on a users score

    • Common Boolean operators #3 - a simple program reads a text files and searches for an inputted score

Python code

# -----------------------------------------------------------
# Common Boolean operators #1
# -----------------------------------------------------------
# Assign a Boolean value to a and b
a = True
b = False

# Print the result of a and b
print("a and b:", a and b)
# Print the result of a or b
print("a or b:", a or b)
# Print the result of not a
print("not a:", not a)


# -----------------------------------------------------------
# Common Boolean operators #2
# -----------------------------------------------------------
# Take input for the score from the user
score = int(input("Enter the score: "))

# Compare the score and output the corresponding grade
if score >= 90 and score <= 100:
    print("Grade: A")
elif score >= 80 and score < 90:
    print("Grade: B")
elif score >= 70 and score < 80:
    print("Grade: C")
elif score < 70:
    print("Fail")


# -----------------------------------------------------------
# Common Boolean operators #3
# -----------------------------------------------------------
# Open the file for reading
try:
    file = open("scores.txt", "r")
    
    # Set flags to false
    end_of_file = False
    found = False
    score = input("Enter a score: ")

    # While it's not the end of the file and the score has not been found
    while not end_of_file and not found:
        # Read the line
        scores = file.readline().strip()

        # If the line equals the score
        if score == str(scores):
            found = True
            print("Score found")
        
        # If the line is empty (i.e., end of file)
        if scores == "":
            end_of_file = True
            if not found:
                print("Score not found")
    
    # Close the file after reading
    file.close()

except FileNotFoundError:
    print("The file 'scores.txt' was not found.")

Examiner Tips and Tricks

  • Boolean operators are often used in conditional statements such as if, while, and for loops

  • Boolean operators can be combined with comparison operators

  • Be careful when using the NOT operator, as it can sometimes lead to unexpected results

  • It is always a good idea to test your code with different inputs to ensure that it works as expected

Last updated:

You've read 0 of your 5 free revision notes this week

Sign up now. It’s free!

Join the 100,000+ Students that ❤️ Save My Exams

the (exam) results speak for themselves:

Did this page help you?

Robert Hampton

Author: Robert Hampton

Expertise: Computer Science Content Creator

Rob has over 16 years' experience teaching Computer Science and ICT at KS3 & GCSE levels. Rob has demonstrated strong leadership as Head of Department since 2012 and previously supported teacher development as a Specialist Leader of Education, empowering departments to excel in Computer Science. Beyond his tech expertise, Robert embraces the virtual world as an avid gamer, conquering digital battlefields when he's not coding.

James Woodhouse

Author: James Woodhouse

Expertise: Computer Science

James graduated from the University of Sunderland with a degree in ICT and Computing education. He has over 14 years of experience both teaching and leading in Computer Science, specialising in teaching GCSE and A-level. James has held various leadership roles, including Head of Computer Science and coordinator positions for Key Stage 3 and Key Stage 4. James has a keen interest in networking security and technologies aimed at preventing security breaches.