Basic Operators
Lesson 4: Basic Operators
In this lesson, we will explore the fundamental operators in Python that allow us to perform various operations on data. Understanding these operators is crucial for manipulating data, making decisions, and controlling the flow of your programs. We will cover three main types of operators: arithmetic operators, comparison operators, and logical operators. By the end of this lesson, you will be able to use these operators effectively in your Python programs.
Learning Objectives
By the end of this lesson, you will be able to: - Understand and use arithmetic operators to perform mathematical calculations. - Use comparison operators to compare values and make decisions. - Apply logical operators to combine multiple conditions. - Recognize common mistakes when using operators and how to avoid them.
1. Arithmetic Operators
Arithmetic operators are used to perform mathematical operations on numbers. In Python, the following arithmetic operators are available:
| Operator | Description | Example |
|---|---|---|
+ |
Addition | 5 + 3 |
- |
Subtraction | 5 - 3 |
* |
Multiplication | 5 * 3 |
/ |
Division | 5 / 3 |
// |
Floor Division | 5 // 3 |
% |
Modulus (Remainder) | 5 % 3 |
** |
Exponentiation | 5 ** 3 |
Let's look at each operator in detail with examples.
1.1 Addition (+)
The addition operator + is used to add two numbers together.
result = 5 + 3
print(result) # Output: 8
In this example, we add 5 and 3, and the result is stored in the variable result, which is then printed to the console.
1.2 Subtraction (-)
The subtraction operator - is used to subtract one number from another.
result = 5 - 3
print(result) # Output: 2
Here, 5 minus 3 equals 2, which is printed as output.
1.3 Multiplication (*)
The multiplication operator * is used to multiply two numbers.
result = 5 * 3
print(result) # Output: 15
This multiplies 5 by 3, resulting in 15.
1.4 Division (/)
The division operator / divides one number by another and returns a float.
result = 5 / 3
print(result) # Output: 1.6666666666666667
In this case, 5 divided by 3 gives approximately 1.67.
1.5 Floor Division (//)
The floor division operator // divides and returns the largest whole number (integer) less than or equal to the result.
result = 5 // 3
print(result) # Output: 1
Here, 5 // 3 results in 1, discarding the fractional part.
1.6 Modulus (%)
The modulus operator % returns the remainder of a division operation.
result = 5 % 3
print(result) # Output: 2
This means that when 5 is divided by 3, the remainder is 2.
1.7 Exponentiation (**)
The exponentiation operator ** raises a number to the power of another number.
result = 5 ** 3
print(result) # Output: 125
In this example, 5 raised to the power of 3 equals 125.
2. Comparison Operators
Comparison operators are used to compare two values. The result of a comparison operation is always a boolean value (True or False). Here are the comparison operators available in Python:
| Operator | Description | Example |
|---|---|---|
== |
Equal to | 5 == 3 |
!= |
Not equal to | 5 != 3 |
> |
Greater than | 5 > 3 |
< |
Less than | 5 < 3 |
>= |
Greater than or equal to | 5 >= 3 |
<= |
Less than or equal to | 5 <= 3 |
2.1 Equal to (==)
The equal to operator == checks if two values are equal.
result = (5 == 5)
print(result) # Output: True
This checks if 5 is equal to 5, which is True.
2.2 Not equal to (!=)
The not equal to operator != checks if two values are not equal.
result = (5 != 3)
print(result) # Output: True
Here, 5 is not equal to 3, so the result is True.
2.3 Greater than (>)
The greater than operator > checks if the left value is greater than the right value.
result = (5 > 3)
print(result) # Output: True
This checks if 5 is greater than 3, which is True.
2.4 Less than (<)
The less than operator < checks if the left value is less than the right value.
result = (5 < 3)
print(result) # Output: False
In this case, 5 is not less than 3, so the result is False.
2.5 Greater than or equal to (>=)
The greater than or equal to operator >= checks if the left value is greater than or equal to the right value.
result = (5 >= 5)
print(result) # Output: True
Here, 5 is equal to 5, so the result is True.
2.6 Less than or equal to (<=)
The less than or equal to operator <= checks if the left value is less than or equal to the right value.
result = (5 <= 3)
print(result) # Output: False
In this example, 5 is not less than or equal to 3, so the result is False.
3. Logical Operators
Logical operators are used to combine conditional statements. The three primary logical operators in Python are:
| Operator | Description | Example |
|---|---|---|
and |
Returns True if both statements are true | (5 > 3) and (3 < 5) |
or |
Returns True if one of the statements is true | (5 > 3) or (3 > 5) |
not |
Reverses the result of the statement | not(5 > 3) |
3.1 Logical AND (and)
The and operator returns True if both conditions are true.
result = (5 > 3) and (3 < 5)
print(result) # Output: True
In this case, both conditions are true, so the result is True.
3.2 Logical OR (or)
The or operator returns True if at least one of the conditions is true.
result = (5 > 3) or (3 > 5)
print(result) # Output: True
Here, the first condition is true, so the result is True.
3.3 Logical NOT (not)
The not operator reverses the result of the condition.
result = not(5 > 3)
print(result) # Output: False
In this case, since 5 > 3 is true, applying not makes it false.
4. Common Mistakes and How to Avoid Them
- Confusing Assignment with Equality: One common mistake is confusing the assignment operator
=with the equality operator==. Remember that=assigns a value, while==checks for equality. - Not Using Parentheses: When combining multiple conditions with logical operators, use parentheses to ensure the correct order of operations. For example,
andhas higher precedence thanor. - Division by Zero: Be careful when performing division operations. Attempting to divide by zero will raise a
ZeroDivisionErrorin Python.
5. Best Practices
- Use Descriptive Variable Names: When using operators, it’s often helpful to use descriptive variable names that indicate what the variable represents. This makes your code more readable.
- Keep Expressions Simple: Try to keep your expressions simple and easy to understand. If an expression is too complex, consider breaking it down into multiple steps.
- Test Your Code: Always test your code with different values to ensure that it behaves as expected.
Key Takeaways
- Arithmetic operators perform basic mathematical operations.
- Comparison operators evaluate relationships between values and return boolean results.
- Logical operators combine conditions to control the flow of your program.
- Understanding operator precedence is crucial for writing correct expressions.
In this lesson, we have covered the basic operators in Python, including arithmetic, comparison, and logical operators. You should now feel comfortable using these operators in your own programs. In the next lesson, we will dive into working with strings, exploring how to manipulate and format text data in Python.
Get ready to learn how to handle textual data and make your programs even more dynamic!
Exercises
- Exercise 1: Create a program that calculates the area of a rectangle. Use the formula: Area = width * height. Prompt the user for width and height values.
- Exercise 2: Write a program that takes two numbers from the user, compares them using comparison operators, and prints whether the first number is greater than, less than, or equal to the second number.
- Exercise 3: Create a simple calculator that can add, subtract, multiply, and divide two numbers based on user input. Prompt the user for two numbers and the desired operation.
- Exercise 4: Write a program that calculates the total cost of items in a shopping cart. Use a list to store item prices, and then calculate the total using arithmetic operators.
- Practical Assignment: Build a simple number guessing game. The program should generate a random number between 1 and 100, and the user must guess the number. Provide feedback on whether the guess is too high, too low, or correct, using comparison operators to evaluate the guesses.
Summary
- Arithmetic operators perform mathematical operations like addition, subtraction, multiplication, and division.
- Comparison operators compare values and return
TrueorFalsebased on the comparison. - Logical operators combine multiple conditions to control program flow.
- Always be mindful of operator precedence and use parentheses for clarity.
- Testing and debugging are essential to ensure your code works as expected.