Working with Numbers and Arithmetic Operators in Python
In this lesson, we'll explore how to use numbers and arithmetic operators in Python. Numbers are a fundamental data type in programming, and understanding how to manipulate them is essential for solving real-world problems.
Types of Numbers in Python
Python supports two main types of numbers:
- Integers (int): Whole numbers without decimal points, such as 5, -3, or 42.
- Floating-Point Numbers (float): Numbers with decimal points, like 3.14, -0.001, or 2.0.
You can perform various operations on these numbers using arithmetic operators.
Basic Arithmetic Operators
Python provides several built-in operators to perform calculations:
- Addition (+): Adds two numbers. Example:
5 + 3 = 8
. - Subtraction (-): Subtracts one number from another. Example:
10 - 7 = 3
. - Multiplication (*): Multiplies two numbers. Example:
6 * 4 = 24
. - Division (/): Divides one number by another. Example:
8 / 2 = 4.0
. - Modulus (%): Returns the remainder of division. Example:
9 % 4 = 1
. - Exponentiation (**): Raises a number to the power of another. Example:
2 ** 3 = 8
. - Floor Division (//): Divides and rounds down to the nearest whole number. Example:
7 // 2 = 3
.
Example Code
Here's an example demonstrating these operators:
a = 10
b = 3
print(a + b) # Output: 13
print(a - b) # Output: 7
print(a * b) # Output: 30
print(a / b) # Output: 3.333...
print(a % b) # Output: 1
print(a ** b) # Output: 1000
print(a // b) # Output: 3
Advanced Math Operations
For more complex mathematical tasks, Python includes the math
module. Here's how you can use it:
import math
print(math.sqrt(16)) # Square root: Output: 4.0
print(math.pow(2, 3)) # Exponentiation: Output: 8.0
print(math.pi) # Value of Pi: Output: 3.14159...
By mastering numbers and arithmetic operators, you'll have the foundation to tackle more advanced topics in Python programming.