if语句否定python 2.7.8

Ale*_*lex 0 python if-statement negation

嗨,我对编码很新,我坚持否定以及如何正确实现它.我已经经历教科书自学,我卡壳"写一个声明,如果否定N,当且仅当它小于0"

我已经尝试过并且失败了,任何提示或帮助将不胜感激.

if -n > 0:
n = 1
Run Code Online (Sandbox Code Playgroud)

Rob*_*sen 5

像这样?

if n < 0:
    n = -n
Run Code Online (Sandbox Code Playgroud)

if语句检查是否n小于零.如果是这样的情况下,将其分配-nn,有效地否定n.

如果您n使用实际数字替换,您将看到它是如何工作的:

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
Run Code Online (Sandbox Code Playgroud)