首页 > 解决方案 > 当单个 if 语句为真时,如何获得假值?

问题描述

对不起,如果这是重复的问题。这是我第一次使用 StackOverflow。我也是 Python 的初学者。

所以,这里是代码。

def count_positives_sum_negatives(arr):
    #your code here
  array = [0, 0] #array[0] for sum of positives.  array[1] for sum of negatives.

  for x in arr:
    if x > 0:
      array[0] = array[0] + x
      print(array)



count_positives_sum_negatives([1,2,3,4,-5])

基本上,我想创建一个包含正数总和和负数总和的数组。对于给定的数组,它应该返回[10, -5]. 现在,我想学习和理解一些东西,当单个 if 语句为 true 时,我怎样才能得到 false 值?我正在考虑双 if 语句或 while 循环,但这可能与单 if 语句吗?
当 if 语句条件为真时,数组变为 [10, 0] 所以现在我有了正数的总和。我应该如何-5使用单个 if 语句获得否定值的总和?

问题2:为什么我得到一个重复的值?我不习惯return停止循环,所以我对这段代码感到困惑。

for x in arr:
    while x > 0:
       print(x) # Print 1 again and again...

标签: pythonarraysfor-loopif-statement

解决方案


对不起,我可以回答我自己的问题。

这里是。

def count_positives_sum_negatives(arr):
    #your code here
  array = [0, 0] #array[0] for sum of positives.  array[1] for sum of negatives.

  for x in arr:
    if x > 0:
      array[0] = array[0] + x
    else:
      array[1] = array[1] + x
    print(array)



count_positives_sum_negatives([1,2,3,4,-5])

谢谢你们的帮助。


推荐阅读