You'll begin your Python journey with a fundamental understanding of numbers. Numbers are the building blocks of any programming language, allowing you to perform calculations and store values. In this lesson, we will cover three types of numbers: integers (int), floating-point numbers (float), and complex numbers (complex). By mastering these concepts, you'll be well on your way to creating powerful Python programs!
An integer is a whole number without decimal points. Examples include 0
, 7
, -5
. You can use integers for counting items, such as the number of apples in a basket or the number of times a loop executes.
Floating-point numbers are real numbers that can have decimal points. Examples include 3.14
, 0.0001
, and -2.5
. They are used to represent measurements with decimals, such as weight, temperature, or distance.
Complex numbers consist of a real part and an imaginary part. The general form is a + bi
, where a
is the real part, b
is the imaginary part, and i
is the square root of -1. Complex numbers are used in various mathematical and scientific applications, like solving equations with imaginary roots or calculating Fourier transforms.
Let's dive into some examples:
# Integers
integer_value = 42
print(integer_value) # Output: 42
# Floating-point numbers
float_value = 3.14159
print(float_value) # Output: 3.14159
# Complex numbers
complex_value = 1 + 2j
print(complex_value) # Output: (1+2j)
What causes it: Attempting to perform an operation with incompatible types, such as adding an integer and a float.
# Bad code example that triggers the error
integer_value = 42
float_value = 3.14
print(integer_value + float_value)
Error message:
TypeError: unsupported operand type(s) for +: 'int' and 'float'
Solution: Ensure that both operands are of the same type before performing an operation.
# Corrected code
integer_value = 42
float_value = 3.14
print(float(integer_value) + float_value)
Why it happens: Incompatible types cannot be directly combined in Python without proper conversion.
How to prevent it: Always ensure that both operands are of the same type before performing an operation or use a function like float()
or int()
to convert one value to the desired type.
Next steps: Build upon your knowledge of numbers by learning about variables, data types, and operators in Python! Keep practicing and exploring the Python documentation for more insights into this powerful programming language. Happy coding!