Reputation: 37
Here's my code:
variable1=201
variable2=202
if variable1==variable2:
print ("done")
I want my code to recognise that the numbers are close to being equal and print "done". I want the computer to print "done" if the difference between the two numbers is less than or equal to 5.
Upvotes: 2
Views: 6478
Reputation: 3424
Could use:
variable1 = 201
variable2 = 202
if variable1 - variable2 in range(-5,5):
print('Done')
Upvotes: 0
Reputation: 160417
You can either subtract them and evaluate their absolute value as Patrick suggests or you could utilize isclose
from the math
module with a similar effect, if you're using Python >= 3.5
.
Though suggested, isclose
is probably not the best if you're starting out since the tolerance arguments might confuse, so I'd go with abs(variable1 - variable2) <= 5
if I were you.
Upvotes: 4