Numeric Data Types (int, float)
In Python, you can work with various numeric data types, including integers and floating-point numbers. These data types are essential for performing mathematical operations and representing different types of numerical data.
1. Integer (int)
Integers are whole numbers, both positive and negative, without any decimal point. You can use them to represent quantities, counts, and indices. In Python, you can declare integer variables as follows:
# Integer variables
x = 5
y = -10
You can perform various mathematical operations with integers, such as addition, subtraction, multiplication, and division.
a = 10
b = 5
addition = a + b # 15
subtraction = a - b # 5
multiplication = a * b # 50
division = a / b # 2.0 (result is a float)
2. Floating-Point (float)
Floating-point numbers, or floats, are used to represent numbers with a decimal point or in scientific notation. Floats are essential for calculations that require precision. You can declare float variables like this:
# Float variables
pi = 3.14159
temperature = -10.5
Floats can be involved in various mathematical operations as well, such as addition, subtraction, multiplication, and division.
x = 5.5
y = 2.0
addition = x + y # 7.5
subtraction = x - y # 3.5
multiplication = x * y # 11.0
division = x / y # 2.75
3. Type Conversion
You can convert between int and float types using type conversion functions:
- To convert an int to a float, use the
float()
function. - To convert a float to an int, use the
int()
function (this truncates the decimal part).
integer_number = 10
float_number = 3.14
converted_to_float = float(integer_number) # 10.0
converted_to_int = int(float_number) # 3
4. Mathematical Operations
Python supports a wide range of mathematical operations for both int and float types, including:
- Addition (
+
) - Subtraction (
-
) - Multiplication (
*
) - Division (
/
) - Modulus (remainder) (
%
) - Exponentiation (
**
) - Floor Division (
//
)
a = 10
b = 3
addition = a + b # 13
subtraction = a - b # 7
multiplication = a * b # 30
division = a / b # 3.3333333333333335
modulus = a % b # 1
exponentiation = a ** b # 1000
floor_division = a // b # 3
Understanding and using these numeric data types and their operations is crucial for any programming that involves calculations. In the next sections, we'll explore more complex operations and functions available in Python for numeric data.