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
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
Negation requires assigning a value to n. "If and only if" requires an if statement.
if n < 0:
n = -n
if n < 0:
n = n * -1
print n
I think this is as simple as it gets for a beginner.
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
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: ...
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.