Lightning bolt and Python code snippet with "Python Operators" in blocky caps

Python Operators

Now that you’ve learned about variables and how to store different data types let’s look at basic operations and expressions. By the end of this lesson, you’ll be able to perform basic arithmetic (do maths!), work with comparison and logical operators, and combine them to create more complex expressions. Get you!

Arithmetic Operators

Python provides built-in arithmetic operators, allowing you to do basic maths. Here are the main ones:

OperatorDescriptionExampleResult
+Addition5 + 38
-Subtraction10 - 46
*Multiplication2 * 714
/Division15 / 35.0
%Modulus (remainder)10 % 31
**Exponentiation2 ** 38
//Floor Division7 // 23

Examples:

a = 10
b = 3

# Addition
print(a + b)  # Output: 13

# Subtraction
print(a - b)  # Output: 7

# Multiplication
print(a * b)  # Output: 30

# Division (returns float)
print(a / b)  # Output: 3.3333...

# Modulus (remainder)
print(a % b)  # Output: 1

# Exponentiation (a raised to the power of b)
print(a ** b)  # Output: 1000

# Floor Division (quotient without remainder)
print(a // b)  # Output: 3

Order of Operations (PEMDAS)

When I was at school we learned BODMAS, which I still remember stands for:

  1. Brackets
  2. Of
  3. Division
  4. Multiplication
  5. Addition
  6. Subtraction

This handy acronym helped me remember the order of operations. Basically, you multiply before you add, and brackets (as I used to call parentheses when I was small) trump everything. Python has very similar rules for these mathematical operations, and the order in which they are applied is called “precedence”. Here’s an example:

result = (2 + 3) * 5  # Output: 25 (Parentheses first, then multiplication)
result = 2 + 3 * 5    # Output: 17 (Multiplication before addition)

Assignment Operators

In Python, assignment operators are used to give values to variables. You’re already familiar with the = operator, but there are shorthand operators that combine arithmetic with assignment:

OperatorDescriptionExampleEquivalent To
=Assignx = 5x = 5
+=Add and Assignx += 3x = x + 3
-=Subtract and Assignx -= 2x = x - 2
*=Multiply and Assignx *= 4x = x * 4
/=Divide and Assignx /= 2x = x / 2
%=Modulus and Assignx %= 3x = x % 3
**=Exponent and Assignx **= 2x = x ** 2
//=Floor Division and Assignx //= 3x = x // 3

Examples:

x = 10
x += 5  # Now x is 15
x *= 2  # Now x is 30
x /= 3  # Now x is 10.0

Comparison Operators

In a computer program, we often have to do things based on comparisons. In Python, we can use the following operators to compare values, which revaluate to True or False depending on the values.

OperatorDescriptionExampleResult
==Equal to5 == 5True
!=Not equal to5 != 3True
>Greater than7 > 5True
<Less than5 < 10True
>=Greater than or equal to8 >= 8True
<=Less than or equal to4 <= 5True

Examples:

a = 10
b = 20

print(a == b)   # Output: False
print(a != b)   # Output: True
print(a > b)    # Output: False
print(a &lt; b)    # Output: True

Logical Operators

Logical operators allow you to combine multiple conditions. We will use these again and again in later projects. You will soon discover that almost every program contains logical checks.

OperatorDescriptionExampleResult
andTrue if both conditions are trueTrue and FalseFalse
orTrue if at least one condition is trueTrue or FalseTrue
notReverses the boolean valuenot TrueFalse

Examples:

x = 5
y = 10
z = 15

# Both conditions must be true for the result to be True
print(x &lt; y and y &lt; z)  # Output: True

# At least one condition must be true for the result to be True
print(x > y or y &lt; z)   # Output: True

# The "not" operator reverses the result
print(not(x &lt; y))  # Output: False

Combining Operators in Expressions

You can combine arithmetic, comparison, and logical operators to create more complex expressions.

Example:

age = 20
income = 50000

# Check if the person is an adult and earns over 40,000
result = (age >= 18) and (income > 40000)
print(result)  # Output: True

In this example, we combined two conditions using logical operators (and) and comparison operators (>= and >).

Basic Input and Output with Expressions

You can use the input() function to get values from the user, and then perform operations on those values.

Example:

# Ask the user for two numbers and print their sum
num1 = int(input("Enter the first number: "))
num2 = int(input("Enter the second number: "))

# Calculate the sum and display it
sum = num1 + num2
print(f"The sum is: {sum}")

Explanation:

  • input() collects data from the user as a string. We use int() to convert that string to an integer.
  • The sum of the two numbers is calculated and displayed using print().

Key Concepts Recap

  • Arithmetic operators: Used for basic math operations like addition (+), subtraction (-), multiplication (*), division (/), and more.
  • Assignment operators: Combine math operations with assignment, such as +=, -=, etc.
  • Comparison operators: Compare values and return True or False, such as ==, !=, >, <.
  • Logical operators: Combine multiple conditions, using and, or, and not.
  • Expressions: You can combine these operators to form complex expressions.

Exercises

  1. Write a program that asks the user for two numbers and performs all the basic arithmetic operations (+, -, *, /, %, **, //) on them. Print the results.
  2. Write a program that asks the user for their age and income. Check if the user is both over 18 years old and earns more than $40,000, and print True or False based on the conditions.
  3. Create a program that uses the modulus operator to determine if a number entered by the user is even or odd.

Next time, we’ll look at strings and explore how to work with text in your programs.

FAQ

Q1: What’s the difference between / and // in Python?

A1: The / operator performs regular division and always returns a floating-point number, even if the result is a whole number. For example, 10 / 5 will return 2.0. The // operator is used for floor division, which returns the result of division rounded down to the nearest whole number (it “floors” the result). For example, 10 // 3 will return 3, ignoring the remainder.

Q2: Why does Python return 5.0 instead of 5 when I divide two integers?

A2: In Python, the / operator always returns a floating-point number, even if the result is a whole number. This is to ensure consistency when performing division. For example, 10 / 2 will return 5.0 instead of 5. If you want an integer result, you can use floor division (//).

Q3: Can I combine different types of operators in one expression?

A3: Yes, you can combine arithmetic, comparison, and logical operators in one expression. Python evaluates them according to their precedence (PEMDAS rules: parentheses, exponents, multiplication/division, and addition/subtraction). You can also use parentheses to control the order of operations. For example:

result = (5 + 3) > 7 and (10 - 2) &lt; 9

This expression first evaluates the arithmetic operations, then the comparison, and finally the logical and.

Q4: Why am I getting a TypeError when I try to add a number and a string?

A4: Python doesn’t allow you to directly add a number and a string. If you try to do something like this:

print("The answer is: " + 42)

You’ll get a TypeError because Python doesn’t know how to combine a string with a number. To fix this, you need to convert the number to a string using str():

print("The answer is: " + str(42))

Alternatively, you can use an f-string to handle this automatically:

print(f"The answer is: {42}")

Q5: What’s the difference between = and == in Python?

A5: The = operator is the assignment operator. It’s used to assign a value to a variable, like this:

x = 5

The == operator is the comparison operator. It checks if two values are equal and returns True or False, like this:

x == 5  # This checks if x is equal to 5

A common mistake is to use = instead of == in conditional statements.

Q6: How does Python handle the order of operations?

A6: Python follows the standard mathematical rules for the order of operations, also known as PEMDAS (Parentheses, Exponents, Multiplication/Division, Addition/Subtraction). Operations inside parentheses are evaluated first, followed by exponents, then multiplication and division (from left to right), and finally addition and subtraction (from left to right).

For example:

result = 2 + 3 * 5  # Output: 17 (multiplication first, then addition)
result = (2 + 3) * 5  # Output: 25 (parentheses first, then multiplication)

Q7: Why is the result of 10 % 3 equal to 1?

A7: The % operator is the modulus operator, which returns the remainder of a division. In the case of 10 % 3, when you divide 10 by 3, the quotient is 3 (3 times 3 is 9), and the remainder is 1. So, 10 % 3 returns 1.

Q8: What happens if I try to divide by zero in Python?

A8: Dividing by zero is mathematically undefined, and in Python, it will raise a ZeroDivisionError. For example:

result = 10 / 0  # Raises a ZeroDivisionError

You should always handle division carefully, especially when user input is involved, and check for potential zero values before performing the operation.

Q9: How do logical operators like and, or, and not work in Python?

A9: Logical operators allow you to combine multiple conditions. Here’s how they work:

  • and: Returns True if both conditions are true. If any condition is false, it returns False. For example:
  True and False  # Output: False
  True and True   # Output: True
  • or: Returns True if at least one of the conditions is true. For example:
  True or False  # Output: True
  False or False  # Output: False
  • not: Reverses the result of a condition. If the condition is True, it becomes False, and vice versa. For example:
  not True  # Output: False
  not False  # Output: True

Q10: What’s the difference between a += 5 and a = a + 5?

A10: There is no functional difference between a += 5 and a = a + 5. Both statements increment the value of a by 5. The += operator is just a shorthand for the longer a = a + 5. Python provides several such shorthand assignment operators for convenience, like -=, *=, /=, etc.

Q11: Why does Python return True for 0 == False and False for 1 == False?

A11: In Python, the number 0 is considered falsy, meaning it behaves like False in boolean contexts. Any non-zero number (like 1) is considered truthy and behaves like True. So:

0 == False  # Output: True
1 == False  # Output: False

This concept is useful when writing conditions in if statements, where you don’t have to explicitly compare values to True or False.

Q12: How can I force Python to return an integer result in division?

A12: You can use the floor division operator // to ensure the result of a division is an integer. For example:

result = 10 // 3  # Output: 3 (instead of 3.3333...)

The // operator rounds the result down to the nearest whole number, even if the division result isn’t a whole number.

Q13: Can I use arithmetic operators with strings in Python?

A13: Python allows limited arithmetic operations with strings. You can:

  • Concatenate strings using the + operator:
  greeting = "Hello" + " " + "world!"
  # Output: Hello world!
  • Repeat a string using the * operator:
  repeat = "ha" * 3
  # Output: hahaha

However, you can’t subtract or divide strings, and attempting to do so will result in an error.

Q14: What’s the best way to format output that combines strings and variables?

A14: The most flexible and readable way to combine strings and variables in Python is by using f-strings. F-strings allow you to embed variables directly into a string without needing to manually convert types. For example:

name = "Alice"
age = 25
print(f"My name is {name} and I am {age} years old.")

This approach is simpler than using + for string concatenation, especially when working with different data types.

Q15: Can I store the result of a comparison in a variable?

A15: Yes, you can store the result of any comparison in a variable. Since comparisons return a boolean value (True or False), you can assign the result to a variable for later use. For example:

is_adult = age >= 18
print(is_adult)  # Output: True if age is 18 or more

This can be useful when you want to reuse the result of a condition multiple times in your code.

This FAQ focuses on practical questions that beginners might ask while learning about basic operations and expressions, providing clarity on common points of confusion.

Similar Posts