Python From Beginner to Advanced

0% completed

Previous
Next
Python - Numbers

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.

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.

Python3
Python3

. . . .

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 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.

Python3
Python3

. . . .

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 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.

Python3
Python3

. . . .

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.
  • 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.

Python3
Python3

. . . .

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.

.....

.....

.....

Like the course? Get enrolled and start learning!
Previous
Next