0

How do I set a maximum limit for an integer in Python I tried using an if statement and it works but i thought there might be a better way to do that

code i'm using to do that works fine

f = 100
f = f + 15
if(f > 100):
    f = 100
print(f)

also tried to use a function but it gives an error after a while

def limit(f):
    if(f > 100):
     return 100

calling function

f = limit(f)

like writing two lines of code everytime time f changes is not a big deal but it would be better if there was a shorter way

3 Answers3

4

This can easily be done with the built-in min function

f = min(f, 100)
Quizzarex
  • 167
  • 2
  • 12
1

You can do it in one line as

def limit(x):
    return x if x <= 100 else 100

OR in more pythonic way

def limit(x, max_val=100):
    return x if x <= max_val else max_val
Leo Arad
  • 4,452
  • 2
  • 6
  • 17
1

You don't need to write a function, there is already a function which does what you want:

>>> a = 85
>>> limit = 100
>>> a = min(limit, a + 10)
>>> a
95
>>> a = min(limit, a + 10)
>>> a
100
Asocia
  • 5,935
  • 2
  • 21
  • 46
  • Spot on. Just for the reference, since we don't really know what's expected maximum here, it could mention there is `math.inf`? – Daniel Hao Jan 17 '21 at 14:05