Python int() Function – Tutorial with Examples

The int() function in Python is a built-in function that converts a value to an integer. It is used to convert data of different data types to integers, such as float, string, or Boolean values. The int() function takes one argument and returns an integer if the argument can be converted to an integer, otherwise, it raises a ValueError exception.

Syntax

int(x, base=10)

Parameters

x – the value to be converted to an integer

base – (optional) the base of the number being converted, default value is 10

Return Value

The int() function returns an integer if the argument can be converted to an integer, otherwise, it raises a ValueError exception.

Examples

Example 1: Conversion of String to Integer

str_value = "123"
int_value = int(str_value)
print(int_value)

Output:

123

In this example, a string "123" is converted to an integer using the int() function. The int() function takes the string as an argument and returns the integer representation of the string, which is 123 in this case.

Example 2: Conversion of Float to Integer

float_value = 123.45
int_value = int(float_value)
print(int_value)

Output:

123

In this example, a float value 123.45 is converted to an integer using the int() function. The int() function takes the float value as an argument and returns the integer representation of the float, which is 123 in this case. Note that the decimal part is truncated, not rounded.

Example 3: Conversion of Boolean to Integer

bool_value = True
int_value = int(bool_value)
print(int_value)

Output:

1

In this example, a Boolean value True is converted to an integer using the int() function. The int() function takes the Boolean value as an argument and returns the integer representation of the Boolean, which is 1 for True and 0 for False.

Use Cases

The int() function is widely used in Python for various purposes such as type conversion, mathematical operations, and data validation. Some common use cases are:

  • Converting user input from string to integer for mathematical operations
  • Converting a float to integer for rounding down to the nearest whole number
  • Converting Boolean values to integer for storage or comparison purposes
  • Converting hexadecimal or binary values to integer for easier computation
  • Validating that a user-entered value can be converted to an integer before using it in a program

The int() function is an essential tool for converting data types in Python and is used in various applications and programs to ensure the consistency and accuracy of data.

Leave a Reply

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