Python is a popular programming language that is known for its versatility and ease of use. One of the most commonly used built-in functions in Python is the "int()" function. The "int()" function is used to convert a string or a float to an integer value.
Syntax: The syntax for the int() function is simple. It requires the function name followed by a set of parentheses that contain the value to be converted.
Example 1:
|
number = "25"
number = int(number)
print(number + 10)
|
In this example, the string "25" is converted to an integer value using the int() function. The new integer value is then stored in the "number" variable. Finally, the program adds 10 to the "number" variable and prints the result.
Output:
|
35
|
|
temperature = 32.5
temperature = int(temperature)
print("The temperature is " + str(temperature) + " degrees Fahrenheit.")
|
In this example, the float value "32.5" is converted to an integer value using the int() function. The new integer value is then stored in the "temperature" variable. Finally, the program prints a message that includes the integer value of the temperature.
Output:
|
The temperature is 32 degrees Fahrenheit.
|
One important thing to note when using the int() function is that it can raise a ValueError exception if the value being converted is not a valid integer. For example, if you try to convert the string "hello" to an integer, the int() function will raise a ValueError exception.
Example 3:
|
number = "hello"
number = int(number)
|