簡體   English   中英

Python:局部,全局變量

[英]Python: local, global variables

我正在用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是未知的,盡管事實上我在函數user_turn()的while循環中聲明了此變量。 我怎么解決這個問題? 我不想將引用作為函數的參數發送。 我認為這並不優雅。 有可能以其他方式做到嗎?

編輯:

好的,我然后更改了一點代碼:

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)

以及函數count_xos的主體:

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)

我得到以下輸出:

RUNDA 1
Twoja kolej na zgadywanie!
Próba nr 1: 0011
[0, 2, 0, 1, 0, 0, 0, 1, 0, 0] [2, 2, 0, 0, 0, 0, 0, 0, 0, 0]
1 1
0 0

您可以確定函數count_xos可以正確計數good_number,good_number_and_position可正確計數。 它應該是1 1,但是我不知道為什么在運行方法count_xos之后,變量good_number_and_position,good_number沒有更改?

您最后一次嘗試不返回數字,因此提供的數字不會在您的調用函數中執行。

您的代碼等效於:

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

看一下范圍規則 -最好將范圍保持盡可能小,並為所需的功能提供數據。

如果您在函數內部修改東西,則返回其新值並重新分配它們-如果您通過列表則不可行,它們是可變引用和“自動更新”,因為您通過對數據的引用進行操作:

# 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 

您可以在Python中的功能更改列表值而非變量值中進一步閱讀-看看這些解釋是否更適合您。

暫無
暫無

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

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