-1

Almost There questions

How does "if n is within 10 of either 100 or 200" correlate with using the absolute value function?

I get what absolute value is, but wouldn't there be an easier/cleaner way without using abs()?

Thanks

  • Can you elaborate on which part you don't understand? Are you asking what the `abs` builtin does? – Brian61354270 Feb 17 '21 at 22:11
  • If they read the assignment text, the `abs` function is explained there. – Håken Lid Feb 17 '21 at 22:13
  • Maybe it's the `or` operator that is the cause of the puzzlement? – Håken Lid Feb 17 '21 at 22:15
  • My apologies, I will edit the post – Juan Isaacs Feb 17 '21 at 22:23
  • 1
    Images of code are not acceptable on SO. Please see the [intro tour,](https://stackoverflow.com/tour) the [help center,](https://stackoverflow.com/help) and this post on [how to ask a good question.](https://stackoverflow.com/help/how-to-ask) – ddejohn Feb 18 '21 at 01:39
  • @blorgon dont see anyone else having a problem with it – Juan Isaacs Feb 19 '21 at 00:00
  • 1
    Don't count on it happening again. Had your question included code you were asking for help on, your post would've been closed until the issue was fixed. You were okay here as you were asking more of a conceptual question. It is **always** preferred that you provide code as copy-able text. It is **never** appropriate to include screenshots of code or error messages or data when asking for help on SO. BTW: you should accept Kirk's answer. – ddejohn Feb 19 '21 at 00:13
  • @JuanIsaacs I mean click on the check mark next to their post. – ddejohn Feb 19 '21 at 00:21

1 Answers1

2

Sure: you absolutely could (and I'd say should) write that like:

def almost_there(n):
    return 90 <= n <= 110 or 190 <= n <= 210

which I think more clearly communicates your intent to the next person who touches the code. However, I think your teacher wanted you to be aware of the "idiom" of abs(x - y) <= z for "x is within z of y", because this won't be the last time you ever see it, either in software or in math. In fact, you'll see |x-y|<z in math a lot in certain subjects; for example, here's an article on epsilon-delta proofs.

I think the code I wrote is more Pythonic. That said, you need to look at the code your teacher described and be able to instantly recognize it as the same thing as |x-y|<z, no matter which way it's written.

Kirk Strauser
  • 30,189
  • 5
  • 49
  • 65