0

Hi I'm fairly new to coding and I'm stuck on negation and how to properly implement it. I've been going through a textbook teaching myself and I'm stuck "Write an if statement that negates n, if and only if it is less than 0"

I've tried and failed miserably, any tips or help would be appreciated.

if -n > 0:
n = 1
Robby Cornelissen
  • 91,784
  • 22
  • 134
  • 156
Alex
  • 17
  • 1
  • 1
    Be aware that indentation is crucial for python to work. So `n = 1` must be indented at least one space. – Artjom B. Aug 10 '14 at 12:02
  • While `if -n > 0:` does work, why did you write it that way instead of the more straightforward `if n < 0:`? – abarnert Aug 10 '14 at 12:32

5 Answers5

5

Like this?

if n < 0:
    n = -n

The if statement checks if n is less than zero. If this is the case, it assigns -n to n, effectively negating n.

If you replace n with an actual number, you'll see how it works:

n = -10
if n < 0:   # test if -10 is less than 0, yes this is the case
    n = -n  # n now becomes -(-10), so 10

n = 10
if n < 0:   # test if 10 is less than 0, no this is not the case
    n = -n  # this is not executed, n is still 10
Robby Cornelissen
  • 91,784
  • 22
  • 134
  • 156
1

Negation requires assigning a value to n. "If and only if" requires an if statement.

if n < 0:
    n = -n
verve
  • 775
  • 1
  • 9
  • 21
1
if n < 0:
  n = n * -1

print n  

I think this is as simple as it gets for a beginner.

tareq
  • 1,119
  • 6
  • 14
  • 28
1

Try this.

n = abs(n)

Is the same.. if it's negative, it will be positive, and if it's positive.. it will be still positive

Oscar Bralo
  • 1,912
  • 13
  • 12
1

Usually Python programmers use the not keyword for negating conditionals:

if not -n > 0:
    n = 1

(Although, that example is a bit convoluted and will probably be easier to maintain as if n < 0: ...).

One nice thing about Python conditional expressions is that the use of not can be done in a way that reads naturally to English speakers. For example I can say if 'a' not in 'someword': ... and it's the same (semantically) as if I coded that as if not 'a' in 'someword': ... This is particularly handy when testing object identity using is ... for example: if not a is b: ... (test if 'a' and 'b' are references to the same object) can also be written if a is not b: ...

Jim Dennis
  • 17,054
  • 13
  • 68
  • 116
  • Incidentally one of the things which I most appreciate about Python is that good Python code is more often readable as natural English than any other programming language I've used. Of course there's lots of "myinstance.do_something(someother_thing)" ... which isn't exactly smooth flowing narrative. But it's still nicer to read than most other programming code. – Jim Dennis Aug 10 '14 at 12:08