0% completed
Python supports several types of numeric data, each designed to handle different kinds of mathematical operations. In this lesson, we'll explore three key numeric types:
int
float
complex
We will also discuss to generate random numbers using Python's random
module.
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.
This example demonstrates addition using integers.
Explanation:
a = 10
and b = 3
: Assign integer values to a
and b
.sum = a + b
: Perform addition and store the result in sum
.print("Sum:", sum)
: Output the result of the addition.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.
This example shows addition with floating point numbers, highlighting potential precision issues.
Explanation:
x = 0.1
and y = 0.2
: Assign float values to x
and y
.total = x + y
: Add x
and y
to compute their total.print("Total:", total)
: Display the result, which may show floating point precision artifacts.Complex numbers consist of a real part and an imaginary part. They are often used in scientific and engineering applications.
This example introduces complex numbers and extracts their real and imaginary parts.
Explanation:
z = 1 + 2j
: Assign a complex number to z
.real_part = z.real
and imaginary_part = z.imag
: Access the real and imaginary components of z
.Python's random
module can be used to generate random numbers, which is useful in simulations, testing, and gaming.
This example demonstrates how to generate a random integer within a specified range.
Explanation:
import random
: Include Python's random
module 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.
.....
.....
.....