- 2
Write a Python program to test whether a number is within 100 of 1000 or 2000.
def near_thousand(n): return ((abs(1000 - n) <= 100) or (abs(2000 - n) <= 100)) print(near_thousand(1000)) print(near_thousand(900)) print(near_thousand(800)) print(near_thousand(2200)) Can someone pls explain to me how this code script works ? Especially this part: ((abs(1000 - n) <= 100) or (abs(2000 - n) <= 100)) Thanks a lot
3 Antworten
+ 2
The abs function is getting an absolute value. The value, positive or negative, will be positive. So if abs(1000 - n) <= 100 or if abs(2000 - n) <= 100, the output is true. Do you understand? the reason there must be and absolute value taken is because of you put, for example, 5000 in the function, it will return true because 1000 - 5000 = -4000, which is less than 100
+ 1
Peter Thanks a lot that’s really helpful
0
Hi