簡體   English   中英

使變量根據返回值更新其值

[英]Make a variable update its value based on returns

我遇到了一個問題,因為我必須多次運行相同的 function 並且想要記錄每次運行的總數。

def add(word):
    total_hello=0
    total_world=0
    if word=="hello":
       total_hello+=1
    elif word=="world":
       total_world+=1

    print(total_hello)
    print(total_world)
    return total_hello, total_world

hello=0
world=0
hello, world+=add("hello")
hello, world+=add("world")
hello, world+=add("hello")
print(hello)
print(world)

將 hello 設為變量並嘗試使其 += 返回不起作用。 有什么簡單的方法可以有效地增加回報嗎?

將 hello 設為變量並嘗試使其 += 返回不起作用。 有什么簡單的方法可以有效地增加回報嗎?

您不能只將 function 返回的元組元素添加到左側元組的元素中。 您有以下選擇:

  1. 變量( total_hellototal_world )是 function 的本地變量,每次調用 function 到0時都會重新分配它們。 嘗試將它們移到您的 function 之外並使其成為全球性的。 它們可用於存儲變量的計數。
# Code in Module 1:
total_hello=0
total_world=0

def add(word):
    global total_hello, total_world
    if word=="hello":
       total_hello+=1
    elif word=="world":
       total_world+=1

    return total_hello, total_world


# Code in Module 2:
# from Module1 import *
add("hello")
add("world")
hello, world = add("hello")
print(hello)
print(world)

  1. 有關更 Pythonic 的方式,請參閱答案。

  2. 在 Python 中使用默認的 arguments:

def add(word, total_world=[0], total_hello=[0]):
    if word == "hello":
       total_hello[0] += 1
    elif word == "world":
       total_world[0] += 1

    return total_hello[0], total_world[0]


add("hello")
add("world")
hello, world = add("hello")
print(hello)
print(world)

您可以直接在 function 中使用helloworld

hello=0
world=0
def add(word):
    global hello, world
    if word=="hello":
       hello+=1
    elif word=="world":
       world+=1

    print(hello)
    print(world)

add("hello")
add("world")
add("hello")

print(hello)
print(world)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM