简体   繁体   中英

Adding to a variable inside a loop

previous_num = 0
sum = 0

def num_update():
add_num = current_num - previous_num
    if add_num > 0:
        sum += add_num
        previous_num = current_num
    elif add_num < 0:
        previous_num = current_num

current_num usually increases but sometimes decreases to a lower number than previous.

It's only updating the first element in the list.

list = [a, b, c, d]
for i in list:
    num_update()

Can you elaborate what you're trying to do here? We need context as to what you're trying to achieve.

Face-off, here are a few problems I've spotted though.

previous_num = 0
sum = 0

def num_update():
  add_num = current_num - previous_num
  if add_num > 0:
    sum += add_num
    previous_num = current_num
  elif add_num < 0:
    previous_num = current_num

You were missing the indentation for the first line of your definition

In your for i... list iteration,

You should be using it in the following format:

for i in range(len(list)):
  //code

Let me know if this fixes your issue, if you want to iterate through a list, you need to use the length of the list.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM