Python Integer (with Examples)

In Python, an int, short for “integer,” is a fundamental data type that represents whole numbers. These whole numbers can be positive, negative, or zero. Python integers have unlimited precision, which means they can represent extremely large or small numbers without any limitations on their size.

# Declaring integers
x = 5
y = -10

# Performing arithmetic operations
sum_result = x + y  
difference_result = x - y  
multiplication_result = x * y  
quotient_result = x / y  

# Exponentiation
power_result = x ** 2      # Raises x to the power of 2

# Modulo operation
remainder_result = x % 3       # Computes the remainder when x is divided by 3

1. What is an Integer in Python?

In Python, an int or integer is:

  • Python integers are always whole numbers without a decimal point.
  • Python integers can be positive, negative or zero.
  • Python integers can represent extremely large or small numbers without overflow or underflow issues.
  • Python integers may contain underscores to improve readability.
  • We can perform various arithmetic operations like addition, subtraction, multiplication, and division on integers.
x = 10
y = 12345678987654321
z = 12_34_56

print(x)			# 10
print(y)			# 12345678987654321
print(z)			# 123456

2. Integers can be Octal and Hexadecimal

In Python, we can represent the integers in octal or hexadecimal representations as well.

  • Octal and hexadecimal numbers can be positive and negative but cannot be written in the exponential form.
  • Octals are prefixed with '0o' (zero followed by the letter “o”) and contains digits from 0 to 7.
  • Hexadecimals are prefixed with '0x' (zero followed by the letter “x” – uppercase or lowercase) and contains digits from 0 to 9 or letters from A to F (uppercase or lowercase).
octalInt = 0o22
hexInt = 0xAA

print(octalInt)		# 18
print(hexInt)		# 170

3. Arithmetic Operations

3.1. Addition, Subtraction, Multiplication and Division

These operations are pretty much similar to other languages.

The standard operation of division, which is performed by the / operator, generally returns a floating-point result. Use the floor division operator // to remove the digits after the decimal point.

  • x / y : returns quotient of x and y
  • x // y : returns (floored) quotient of x and y
  • x % y : remainder of x / y
  • divmod(x, y) : the pair (x // y, x % y)
x = 22
y = 5

print (x + y)			# Prints 27
print (x - y)			# Prints 17
print (x * y)			# Prints 110

print (x / y)			# Prints 4.4
print (x // y)			# Prints 4
print (x % y)			# Prints 2
print ( divmod(x, y) )	# Prints (4, 2)

3.2. Increment and Decrement

In Python, we can increment and decrement integer variables using the += and -= operators, respectively.

  • Increment (+=x) adds x to the operand.
  • Decrement (-=x) subtracts x to the operand.
x = 10
y = 10

x += 1
print (x)	# Prints 11

x += 5
print (x)	# Prints 16

y -= 1
print (y)	# Prints 9

y -= 5
print (y)	# Prints 4

3.3. Exponent

In Python, we can perform exponential calculations using the ‘base ** exponent‘ operator. This operator raises a base number to a specified exponent power.

  • base: This is the base number we want to raise to a power.
  • exponent: This is the power to which we want to raise the base.
x = 10
y = 2

print (x ** y)	# Prints 100

4. Type Checking using isinstance() and type()

In Python, both the isinstance() function and the type() function are used to check the data type of a variable, including whether it is an integer (int).

The isinstance() function is a more flexible way to check if a variable is of a certain type or if it belongs to a specific class.

x = 42

if isinstance(x, int):
    print("x is an integer")
else:
    print("x is not an integer")

The type() function, on the other hand, returns a type object that represents the type of the variable. To check if a variable is an integer using type(), we would compare the result of type(x) to the int type:

x = 42

if type(x) is int:
    print("x is an integer")
else:
    print("x is not an integer")

5. Convert Integer to String

In Python, we can convert an integer to a string using the str() function. This function takes an argument (in this case, an integer) and returns a string representation of that integer.

integer_value = 42

string_value = str(integer_value)

After converting an integer to a string, we can perform string operations on it, such as concatenation, slicing, or formatting. If we do not intend to perform string operations and only want to format it for display purposes, consider using format() function.

formatted_string = "The number is {}".format(integer_value)

6. Convert String to Integer

We can convert a string to an integer using the int() constructor. It takes a string argument and attempts to convert it into an integer.

string_value = '10'

int_value = int( string_value ) 	# 10

If the string cannot be converted to an integer (e.g., if it contains non-numeric characters), it will raise a ValueError exception. We can handle this by adding error checking and exception handling if needed.

string_value = "abc"

try:
    integer_value = int(string_value)
    print(integer_value)
except ValueError:
    print(f"Cannot convert '{string_value}' to an integer.")

7. Conclusion

Integers, represented by the int data type in Python, are a fundamental building block of numerical operations from basic arithmetic to complex mathematical and scientific computations.

The best part is that Python integers have unlimited precision, which allows them to represent extremely large or small numbers without any limitations on size.

Happy Learning !!

Comments

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions and frequently asked interview questions.

Our Blogs

REST API Tutorial

Dark Mode

Dark Mode