Chapter 3: Operators and Expressions in Python
Explore Python operators, including arithmetic, comparison, and logical operators, to create expressions that form the logic of your programs.
In this chapter, we�ll dive into the types of operators in Python and how they can be used to create meaningful expressions. By the end, you�ll have a solid understanding of how to use operators to build logic into your code.
Arithmetic Operators
Arithmetic operators are used to perform mathematical operations. Python supports basic operators such as addition, subtraction, multiplication, and division:
- + (Addition): Adds two numbers.
- - (Subtraction): Subtracts one number from another.
- * (Multiplication): Multiplies two numbers.
- / (Division): Divides one number by another, returning a float.
- % (Modulus): Returns the remainder of division.
- // (Floor Division): Divides and returns the integer part of the result.
- ** (Exponent): Raises a number to the power of another.
a = 10
b = 3
print(a + b) # 13
print(a - b) # 7
print(a * b) # 30
print(a / b) # 3.333...
print(a % b) # 1
print(a // b) # 3
print(a ** b) # 1000
Comparison Operators
Comparison operators are used to compare values. These operators return True
or False
based on the result of the comparison:
- ==: Checks if two values are equal.
- !=: Checks if two values are not equal.
- >: Checks if the left value is greater than the right.
- <: Checks if the left value is less than the right.
- >=: Checks if the left value is greater than or equal to the right.
- <=: Checks if the left value is less than or equal to the right.
x = 5
y = 10
print(x == y) # False
print(x != y) # True
print(x < y) # True
print(x > y) # False
print(x <= y) # True
print(x >= y) # False
Logical Operators
Logical operators allow you to combine multiple conditions. They include and
, or
, and not
:
- and: Returns
True
if both conditions are true. - or: Returns
True
if at least one condition is true. - not: Reverses the result of a condition.
a = True
b = False
print(a and b) # False
print(a or b) # True
print(not a) # False
Combining Operators in Expressions
Operators can be combined to create complex expressions. Use parentheses to control the order of operations:
x = 10
y = 5
z = 2
result = (x + y) * z > (y - z) or not (x < z)
print(result) # True
In this example, the expression combines arithmetic, comparison, and logical operators to evaluate a complex condition.
Summary and Next Steps
In this chapter, we explored Python�s operators and how to use them in expressions. With these tools, you can start building logical conditions and calculations into your code. In the next chapter, we�ll cover control flow statements such as conditionals and loops.