How to Assign an Infinite Value in Python

Ever wondered how to assign an infinite value to a variable in Python? In this tutorial, we will explore how one can assign an infinite value in Python. This feature can prove handy in various programming scenarios, such as creating loops that never break or setting an upper or lower bound on a value.

Assigning Infinity to a Variable

The easiest way to assign an infinite value in Python is through the float type. Python recognizes the strings ‘inf’ and ‘-inf’ as positive and negative infinity respectively:

The variables positive_infinity and negative_infinity now hold infinite and negative infinite values, respectively.

Checking if a Value is Infinite

You can check if a value is infinite in Python using the math module’s isinf() function. Here is how you can do this:

Using Infinity in Expressions

Infinity values work as you would expect in mathematical expressions:

This code assigns the infinite value of positive_infinity plus 1000 to the variable result.

Full Code

Output:

True
True
inf

In Conclusion

In Python, infinite values can be assigned to variables by converting the string ‘inf’ or ‘-inf’ to a floating-point number. This can be useful in many programming scenarios. One can check if a value is infinite using the isinf() function in Python’s math module, and these infinite values can be used in mathematical expressions as demonstrated above.