- 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

8th Jun 2019, 5:47 PM
Tai
3 odpowiedzi
+ 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
8th Jun 2019, 6:21 PM
Pete Cowling
Pete Cowling - avatar
+ 1
Peter Thanks a lot that’s really helpful
8th Jun 2019, 10:48 PM
Tai
0
Hi
1st Aug 2023, 12:20 AM
Tijani Faris
Tijani Faris - avatar