Welcome back, aspiring Pythonista! In our last step, we printed our very first message to the screen. Now, let's dive into the fascinating world of numbers in Python. Computers are excellent at crunching numbers, and Python provides us with two primary ways to represent them: integers and floating-point numbers.
Integers, often shortened to 'int', are whole numbers, both positive and negative, without any decimal point. Think of them as counting numbers. Examples include 0, 1, -5, 42, and -1000. Python can handle integers of virtually any size, limited only by your computer's memory!
my_age = 30
number_of_students = 150
negative_score = -10We can also perform standard arithmetic operations with integers:
sum_result = 5 + 3
difference = 10 - 4
product = 6 * 7
quotient = 20 / 4
exponent = 2 ** 3Note that division with integers in Python 3 (which is what we're using) will always result in a floating-point number, even if the result is a whole number. We'll explore this more in the next section.
Floating-point numbers, or 'float' for short, are numbers that have a decimal point. They are used to represent fractional values and can also be used for very large or very small numbers using scientific notation. Examples include 3.14, -0.5, 2.0, and 1.23e6 (which means 1.23 multiplied by 10 to the power of 6).
pi_value = 3.14159
gravity_constant = 6.674e-11
price = 19.99Arithmetic operations with floats work similarly to integers, but with potential nuances regarding precision. When you mix integers and floats in an operation, the result will typically be a float.
half_of_ten = 10 / 2.0
result_with_float = 5 + 2.5In Python, each piece of data has a 'type'. Knowing the type of your data is crucial because it determines what operations you can perform on it. We've just met two fundamental types: int and float. Python is dynamically typed, meaning you don't have to explicitly declare the type of a variable. Python infers it based on the value assigned.
We can use the built-in type() function to inspect the data type of any variable:
print(type(my_age))
print(type(pi_value))This will output <class 'int'> for my_age and <class 'float'> for pi_value, confirming their respective types.
Use integers when you need to represent exact whole numbers, like counts of items, ages, or quantities. Use floating-point numbers when you need to represent values with decimal points, such as measurements, financial calculations, or scientific data. Be mindful that floating-point arithmetic can sometimes have tiny precision errors due to how computers represent decimal numbers internally. For most common tasks, this won't be an issue, but it's something to keep in the back of your mind for highly sensitive calculations.
Congratulations! You've taken a significant step in understanding how Python handles numbers. In the next section, we'll explore other essential data types like strings.