函数不更改变量值

时间:2019-11-12 05:45:54

标签: python

为什么我的函数不更改python中变量的值?

pattern = 0
def patterns(pattern):
    if die1 == die2 == die3 == die4 == die5:
        pattern = 1
        patternDef = "all values being the same (100 points)?"
    elif diceSum % 2 == 1:
        pattern = 2
        patternDef = "a prime number sum (sum of" + str(diceSum) + "is a prime number) (50 points)"
    elif count == 3:
        pattern = 3
        patternDef = "3 values being the same (30 points)?"
    elif count == 0:
        pattern = 4
        patternDef = " all different values (25 points)?"
    else:
        pattern = 5
patterns(pattern)
print(pattern)
OUTPUT:
0

3 个答案:

答案 0 :(得分:1)

因为pattern是局部变量(因为它是一个函数参数),并且在函数退出时不会保留对其的修改。

解决此问题的一种方法是将pattern作为全局变量传递(就像您对die1..5diceSumcount所做的隐式操作一样),但是更好的方法是将骰子值作为参数传入,在此计分函数中计算中介并返回值。我将返回2个元组的模式“ id”和说明,但您可能还希望将其扩展为3个元组的id /说明/分数。

def patterns(die1, die2, die3, die4, die5):
    total = die1 + die2 + die3 + die4 + die5
    count = len({die1, die2, die3, die4, die5})  # count unique values
    if die1 == die2 == die3 == die4 == die5:
        return (1, "all values being the same (100 points)?")
    elif total % 2 == 1:
        return (2, "a prime number sum (sum of %s is a prime number) (50 points)" % total)
    elif count == 3:
        return (3, "3 values being the same (30 points)?")
    elif count == 5:
        return (4, "all different values (25 points)?")
    else:
        return (5, "mysterious pattern #5")

# ...

pattern_id, pattern_explanation = patterns(1, 3, 6, 4, 5)

通过将它们作为列表传递进来,进一步的重构将允许任意数量的骰子:

def patterns(dice):
    total = sum(dice)  # total of dice
    count = len({die1, die2, die3, die4, die5})  # count unique values
    if count == 1:
        return (1, "all values being the same (100 points)?")
    elif total % 2 == 1:
        return (2, "a prime number sum (sum of %s is a prime number) (50 points)" % total)
    elif count == 3:
        return (3, "3 values being the same (30 points)?")
    elif count == len(dice):
        return (4, "all different values (25 points)?")
    else:
        return (5, "mysterious pattern #5")

# ...

print(patterns([1, 3, 3, 6, 2, 4, 5, 5, 1, 5, 1]))

答案 1 :(得分:0)

为了改进前面的答案,每种编程语言中都有一个称为变量作用域的变量。

变量的范围是将变量存储在内存中的程度。一旦变量超出范围,它的值将被丢弃,并释放内存。

在您的情况下,当您将全局变量和函数参数都标记为pattern时,就会发生混淆。

但是由于函数参数的作用域仅扩展到函数主体,因此一旦程序控件从函数中退出,该值将被丢弃,如上一个答案所述。

答案 2 :(得分:0)

不要忘记全局运算符。此代码使您可以更改pattern的值,而无需稍后调用pattern = patterns ()

pattern = 0
def patterns(pattern):
    global pattern
    if die1 == die2 == die3 == die4 == die5:
        pattern = 1
        patternDef = "all values being the same (100 points)?"
    elif diceSum % 2 == 1:
        pattern = 2
        patternDef = "a prime number sum (sum of" + str(diceSum) + "is a prime number) (50 points)"
    elif count == 3:
        pattern = 3
        patternDef = "3 values being the same (30 points)?"
    elif count == 0:
        pattern = 4
        patternDef = " all different values (25 points)?"
    else:
        pattern = 5
patterns()