将整数转换为负数

Shi*_*ifu 1 python

我正在尝试编写一些代码,如果发生某种情况,特定的数字必须更改为 - 该数字.到目前为止,我有以下代码:

x=6

for words in foo:
   if "bar" in words:
      crazy_function(x)
   else:
      pass
Run Code Online (Sandbox Code Playgroud)

如果单词"bar"在单词中,则x将需要为-6,如果不是单词,则需要以+6表示.在某些情况下,x = -6,在这种情况下,如果bar是单词,则需要变为正数.我需要用实际工作的东西替换"crazy_function()".

Loc*_*age 13

使用否定运算符:

x=6

for words in foo:
  if "bar" in words:
    x = -x;
Run Code Online (Sandbox Code Playgroud)


Ósc*_*pez 6

实施"疯狂的功能"是微不足道的:

def crazy_function(x):
    return -x
Run Code Online (Sandbox Code Playgroud)

像这样使用它:

if "bar" in words:
    x = crazy_function(x)
Run Code Online (Sandbox Code Playgroud)

或者简单地说明:

if "bar" in words:
    x = -x
Run Code Online (Sandbox Code Playgroud)

为了让它更短,正如@kroolik指出的那样:

x = -x if "bar" in words else x
Run Code Online (Sandbox Code Playgroud)