Python:局部全局变量

时间:2019-03-03 07:36:42

标签: python python-3.x variables global local

我正在用Python(Mastermind)制作新程序。我对变量的引用有疑问:

def user_turn():
    try_counter = 1
    user_code = []
    guessed_code = random_code()
    print("Twoja kolej na zgadywanie!")
    while try_counter <= max_tries and user_code != guessed_code:
        good_number, good_number_and_position = 0, 0
        appearance_types_guessing_code = [0 for i in range(types)]
        appearance_types_user_code = [0 for i in range(types)]
        user_code = input("Próba nr {}: ".format(try_counter))
        user_code = list(map(int, str(user_code)))
        count_xos()
        print_xos()
        try_counter += 1

    print_result_user_turn()

函数print_xos()的主体:

def print_xos():
    for i in range(good_number_and_position):
        print("x", end='')
    for i in range(good_number):
        print("o", end='')
    print("")

我的问题是函数print_xos()中的变量good_numbergood_number_and_position是未知的,尽管事实上我在函数{{1 }}。我怎么解决这个问题?我不想将引用作为函数的参数发送。我认为这并不优雅。可以用其他方式做到吗?

编辑:

好的,然后我更改了一点代码:

user_turn()

函数count_xos的主体:

def user_turn():
    try_counter = 1
    user_code = []
    guessed_code = random_code()
    appearance_types_guessed_code = [0] * types
    how_many_appearance(guessed_code, appearance_types_guessed_code)
    print("Twoja kolej na zgadywanie!")
    while try_counter <= max_tries and user_code != guessed_code:
        good_number, good_number_and_position = 0, 0
        appearance_types_user_code = [0] * types
        user_code = input("Próba nr {}: ".format(try_counter))
        user_code = list(map(int, str(user_code)))
        how_many_appearance(user_code, appearance_types_user_code)
        print(appearance_types_guessed_code, appearance_types_user_code)
        count_xos(guessed_code, appearance_types_guessed_code, user_code, appearance_types_user_code, good_number, good_number_and_position)
        print(good_number_and_position, good_number)
        print_xos(good_number_and_position, good_number)
        try_counter += 1

    print_result_user_turn(guessed_code, user_code)

我得到了这个输出:

def count_xos(guessed_code, appearance_types_guessed_code, user_code, appearance_types_user_code, good_number, good_number_and_position):
    for i in range(len(appearance_types_guessed_code)):
        good_number += np.min([appearance_types_guessed_code[i], appearance_types_user_code[i]])

    for i in range(code_size):
        if guessed_code[i] == user_code[i]:
            good_number_and_position += 1
            good_number -= 1
    print(good_number_and_position, good_number)

您可以确定函数count_xos可以正确计数good_number,good_number_and_position也可以正确计数。应该是1 1,但是我不知道为什么在运行count_xos方法之后,变量good_number_and_position,good_number都没有更改?

1 个答案:

答案 0 :(得分:0)

您最后一次尝试不返回数字,因此提供的数字不会在您的调用函数中执行。

您的代码等同于:

def one(aa,bb):
    aa *= 2
    bb *= 3
    print("In function", aa, bb)
    return aa, bb

a = 5
b = 11
one(a,b)      # does not reassign returned values - similar to not return anything like yours
print(a,b)

输出:

In function 10 33
5 11   

您需要返回并重新分配值:

a,b = one(a,b) # reassign returns
print(a,b)

输出:

In function 10 33
10 33

看看Scoping rules-最好将范围保持尽可能小,并为所需的功能提供数据。

如果您修改函数中的内容,则返回其新值并重新分配它们-如果您通过列表则不可行,它们是可变引用和“自动更新”,因为您通过对数据的引用进行操作:

# same function used as above

a = 5
b = [11]
one(a,b)
print(a,b)

输出:

In function 10 [11, 11, 11]
5 [11, 11, 11]

如果您查看变量的id(),您会发现更改aa会将名称aa指向其他某个ID,但外部指向a仍然指向原始的。更改列表不会更改引用ID-它会将引用“指向”的数据更改为:

def one_ids(aa,bb):
    print(id(aa),id(bb))
    aa *= 3   # modify an integer
    bb *= 3   # modify the list
    print(id(aa),id(bb))

a = 5
b = [11]
print(id(a),id(b))
one_ids(a,b)
print(id(a),id(b))

输出:

139647789732288   139647790644808   # id of a,b
139647789732288   139647790644808   # id of aa,bb before changing
139647789732**6**08   139647790644808   # id of aa,bb after changing
139647789732288   139647790644808   # id of a,b 

您可以在Function changes list values and not variable values in Python中进一步阅读-看看这些解释是否更适合您。