Python Numbers

Introduction to Numbers

Numbers are the fundamental building blocks for any computations in Python, and understanding how they work is essential. 

In Python, numbers come in different flavors, each suited for specific purposes. Here are the main types:

  • Integers (int): These represent whole numbers, positive, negative, or zero. Examples include 42, -100, and 0. They are great for counting objects or representing whole units.

  • Floats (float): These represent decimal numbers. Examples include 3.14159 (pi), 1.234, and -98.7. They are useful for measurements, calculations involving decimals, or any situation where precise fractional values are needed.

  • Complex numbers (complex): These are a combination of a real number and an imaginary unit (represented by the letter "j"). They are less commonly used in basic programming but are essential in advanced scientific computing. An example is 3 + 4j (where 3 is the real part and 4j is the imaginary part).


Understanding Data Types and Their Importance

Data types define how Python stores and manages information. When you assign a number to a variable, Python understands what kind of number it is based on the data type. This is crucial because:

  • Operations: Different data types have different allowed operations. For example, you can add two integers, but you can't directly add an integer and a string.
  • Memory Efficiency: Python allocates memory differently for each data type. Using the appropriate data type helps optimize memory usage.
  • Accuracy: Floats can lose precision for certain operations due to limitations in how computers store decimals. Integers, on the other hand, provide exact calculations for whole numbers.

Example:

age = 30  # Integer (whole number of years)
price = 9.99  # Float (decimal price)

# You can perform arithmetic operations on numbers of the same type
total_cost = price * 2  # Multiplies two floats

# Mixing data types might require conversion
# age_in_seconds = age * 365  # This would result in an error (integer * float)
age_in_seconds = age * 365.25  # We convert age to float for accurate calculation

It's time to take a quiz!

Test your knowledge and see what you've just learned.

Which of the following represents a whole number in Python?

42
3.14
4 + 5j
"100"
Check Answer

Which of the following is an example of a float in Python?

42
9.99
100j
0
Check Answer

What is the correct representation of a complex number in Python?

5 + 2
3.0 + 4.0
3 + 4j
4 + 5
Check Answer

What will be the result of age * 365.25 if age is an integer 30?

10957.5
10957
10960
30
Check Answer

What happens if you try to add an integer to a string in Python?

It returns None
It works and returns a combined value
It raises a TypeError
It automatically converts the string to an integer
Check Answer