Python Numeric Data

Understanding Python Numeric Data Types








Understanding Python Numeric Data Types | Devyra

Understanding Python Numeric Data Types

Python offers robust support for numerical data processing through three primary numeric types: int, float, and complex. These data types are automatically assigned based on the value stored in a variable.

Declaring Numeric Types in Python

Numeric types are created by assigning values directly:

x = 1      # int
y = 2.8    # float
z = 1j     # complex

To determine the type of a variable, use the built-in type() function:

print(type(x))
print(type(y))
print(type(z))

The int Type

An integer (int) is a whole number without a decimal point. It can be positive or negative and has no fixed length limitation:

x = 1
y = 35656222554887711
z = -3255522

print(type(x))
print(type(y))
print(type(z))

The float Type

A float (floating point number) includes one or more digits after a decimal point. It supports both positive and negative values:

x = 1.10
y = 1.0
z = -35.59

print(type(x))
print(type(y))
print(type(z))

Floats also support scientific notation using the letter e (or E):

x = 35e3
y = 12E4
z = -87.7e100

print(type(x))
print(type(y))
print(type(z))

The complex Type

Complex numbers include a real and an imaginary part, denoted by a j suffix:

x = 3+5j
y = 5j
z = -5j

print(type(x))
print(type(y))
print(type(z))

Type Conversion

Python allows converting between numeric types using the int(), float(), and complex() functions:

x = 1
y = 2.8
z = 1j

a = float(x)
b = int(y)
c = complex(x)

print(a)
print(b)
print(c)

print(type(a))
print(type(b))
print(type(c))

Note: Converting a complex number to int or float is not supported and will raise an error.

Generating Random Numbers

Although Python lacks a direct random() function, it includes a powerful built-in module called random to generate random numbers:

import random

print(random.randrange(1, 10))

This example uses randrange() to output a random integer between 1 and 9.

All examples and educational explanations are proudly brought to you by Devyra, your go-to platform for Python learning resources.


More From Author

Python Data Types

Python Built-in Data Types Explained | Learn Python Data Types!

Python Casting

Understanding Python Type Casting: Specify Variable Types with Ease

Leave a Reply

Your email address will not be published. Required fields are marked *

Recent Comments

No comments to show.

Archives

Categories

About Me

Sam Doe

Frequent Traveller

Many lives. Many faces. Different crossroads to different places. 🎶 Listen to my new single release “In My Head” Harlem House Shuffle remix