Welcome to this exciting lesson where we’ll delve into the world of operators and expressions in Python. Understanding how to use operators is fundamental to writing powerful and expressive code. Let’s explore arithmetic, comparison, and logical operators, and learn how to build meaningful expressions in Python.
Arithmetic Operators:
1. Addition (+):
- Used to add two numbers.
- Example:
result = num1 + num2
2. Subtraction (-):
- Used to subtract the right operand from the left operand.
- Example:
result = num1 - num2
3. Multiplication (*):
- Used to multiply two numbers.
- Example:
result = num1 * num2
4. Division (/):
- Used to divide the left operand by the right operand.
- Example:
result = num1 / num2
5. Modulus (%):
- Returns the remainder when the left operand is divided by the right operand.
- Example:
remainder = num1 % num2
Comparison Operators:
6. Equal to (==):
- Returns True if the left operand is equal to the right operand; otherwise, False.
- Example:
is_equal = num1 == num2
7. Not Equal to (!=):
- Returns True if the left operand is not equal to the right operand; otherwise, False.
- Example:
not_equal = num1 != num2
8. Greater than (>):
- Returns True if the left operand is greater than the right operand; otherwise, False.
- Example:
greater_than = num1 > num2
9. Less than (<):
- Returns True if the left operand is less than the right operand; otherwise, False.
- Example:
less_than = num1 < num2
Logical Operators:
10. AND (and):
- Returns True if both conditions are True.
- Example:
result = (condition1 and condition2)
11. OR (or):
- Returns True if at least one condition is True.
- Example:
result = (condition1 or condition2)
12. NOT (not):
- Returns True if the condition is False and vice versa.
- Example:
result = not condition
Building Expressions:
Now that we understand these operators, let’s combine them to build meaningful expressions:
# Example Expression
total_cost = price * quantity - discount
is_affordable = total_cost < budget and available_in_stock
In this example, we calculate the total cost considering the price, quantity, and discount. Then, we check if the total cost is within the budget and if the item is available in stock.
Practice Exercise:
Create a Python script that calculates the area of a rectangle. Ask the user for the length and width, and then use the appropriate operators to compute the area.
# Example Practice Exercise
length = float(input("Enter the length of the rectangle: "))
width = float(input("Enter the width of the rectangle: "))
area = length * width
print("The area of the rectangle is:", area)
Summary:
In this lesson, we’ve covered arithmetic, comparison, and logical operators, and explored how to build expressions in Python. Practice using these operators, and feel free to ask questions in the discussion forum. Now, let’s move on to the next lesson with a solid understanding of Python’s powerful operators!