Python supports several types of numeric data, each designed to handle different kinds of mathematical operations. In this lesson, we’ll explore four key numeric types: int, float, complex, and discuss generating random numbers using Python’s random module.
Integer Type (int)
Integers are whole numbers without a decimal point, which can be positive or negative. Python’s integers have unlimited precision, which means they can grow as large as the memory your program is allowed to use.
Example
This example demonstrates addition using integers.
Explanation:
a = 10andb = 3: Assign integer values toaandb.sum = a + b: Perform addition and store the result insum.print("Sum:", sum): Output the result of the addition.
Floating Point Type (float)
Floating point numbers represent real numbers and are written with a decimal point to indicate the fractional part. They are useful for representing numbers that require more precision than integers.
Example
This example shows addition with floating point numbers, highlighting potential precision issues.
Explanation:
x = 0.1andy = 0.2: Assign float values toxandy.total = x + y: Addxandyto compute their total.print("Total:", total): Display the result, which may show floating point precision artifacts.
Complex Number Type (complex)
Complex numbers consist of a real part and an imaginary part. They are often used in scientific and engineering applications.
Example
This example introduces complex numbers and extracts their real and imaginary parts.
Explanation:
z = 1 + 2j: Assign a complex number toz.real_part = z.realandimaginary_part = z.imag: Access the real and imaginary components ofz.- The print statements display these parts, clearly separating the real and imaginary components.
Random Numbers
Python’s random module can be used to generate random numbers, which is useful in simulations, testing, and gaming.
Example
This example demonstrates how to generate a random integer within a specified range.
Explanation:
import random: Include Python’srandommodule to use its functionality.rand_num = random.randint(1, 10): Generate a random integer between 1 and 10.print("Random Number:", rand_num): Output the randomly generated number.
This lesson has introduced the basic numeric types in Python, each with a practical example to illustrate their use. These foundational concepts are essential for performing a wide range of mathematical operations in Python.