Python 2.7.8 中的 if 语句否定
你好,我刚开始学习编程,现在在否定这个概念上遇到了困难,不知道怎么正确地使用它。
我在自学一本教科书,但现在卡住了,题目是“写一个if语句,只有当n小于0时才对n进行否定”。
我试过了,但失败得很惨,任何建议或帮助都非常感谢。
if -n > 0:
n = 1
5 个回答
1
试试这个。
n = abs(n)
这两个是一样的.. 如果是负数,它会变成正数;如果是正数,它还是正数。
1
否定操作需要给变量n赋一个值。而“当且仅当”这个概念则需要用到if语句。
if n < 0:
n = -n
1
通常,Python程序员会使用not
这个关键词来否定条件判断:
if not -n > 0:
n = 1
(不过,这个例子有点复杂,可能用if n < 0: ...
会更容易维护。)
Python的条件表达式有个不错的地方,就是使用not
的方式让说英语的人读起来很自然。比如我可以写if 'a' not in 'someword': ...
,这和写成if not 'a' in 'someword': ...
是一样的意思。这在检查对象是否相同的时候特别方便,比如:if not a is b: ...
(测试'a'和'b'是否指向同一个对象)也可以写成if a is not b: ...
1
if n < 0:
n = n * -1
print n
我觉得这对初学者来说已经很简单了。
5
像这样吗?
if n < 0:
n = -n
if
语句用来检查 n
是否小于零。如果是这样,它就把 -n
的值赋给 n
,也就是把 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