Autocodewizard Logo Operators and Expressions in Python -Autocodewizard Ebooks - Python Programming Essentials: A Beginner�s Guide to Code and Data

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:

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:

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:

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.