Hướng dẫn python update variable in if statement - biến cập nhật python trong câu lệnh if

Mọi thứ hoạt động ngoại trừ [current_space] không được cập nhật với [current_space += rolled_dice]. Nó chỉ cập nhật lên giá trị [rolled_dice]. Điều gì gây ra điều này và có thực hành tốt hơn để thực hiện ở đây. Giống như một lớp học?

from random import randint

finish_line = 20
player_1 = raw_input['Enter player 1 name: ']
player_2 = raw_input['Enter player 2 name: ']    
print['\nWelcome ' + player_1 + ' and ' + player_2]
print['\nLet\'s Play!\n']


def roll_1[]:
    current_space1 = int[]
    #print[current_space1]
    roll_dice = raw_input[player_1 + ' roll dice? y or n: ']
    if roll_dice == 'y':
        rolled_dice = [randint[1,6]]
        print[player_1 + ' ' + 'rolled a ' + str[rolled_dice]]
        if current_space1 != finish_line:
            current_space1 += rolled_dice
            #print[current_space1]
            roll_2[]
        elif current_space1 == finish_line:
            print['You are the winner ' + player_1 + '!']
        elif roll_dice == 'n':
            print['Thanks for playing']
        else:
            print['Invalid entry']



def roll_2[]:
    current_space2 = int[]
    roll_dice = raw_input[player_2 + ' roll dice? y or n: ']
    if roll_dice == 'y':
        rolled_dice = [randint[1,6]]
        print[player_2 + ' ' + 'rolled a ' + str[rolled_dice]]
        if current_space2 != finish_line:
            current_space2 += rolled_dice
            roll_1[]
        elif current_space2 == finish_line:
            print['You are the winner ' + player_2 + '!']
        elif roll_dice == 'n':
            print['Thanks for playing']
        else:
            print['Invalid entry']

roll_1[] 

Khi được hỏi ngày 5 tháng 5 năm 2017 lúc 22:20May 5, 2017 at 22:20

Cả current_space1current_space2 đều là các biến cục bộ - chúng được tạo và khởi tạo khi hàm nhập và chỉ có sẵn trong bối cảnh chức năng, một khi bạn rời khỏi hàm hoặc nhập chức năng khác, chúng không khả dụng. Nếu bạn muốn chúng có sẵn bên ngoài chức năng [và tăng trong nhiều cuộc gọi chức năng], bạn cần phải khai báo chúng trên toàn cầu:local variables - they are created and initialized when the function enters and available only within the function context, once you leave the function, or enter another function, they are not available. If you want them to be available outside of the function [and increment within multiple function calls] you need to declare them globally:

finish_line = 20
player_1 = raw_input['Enter player 1 name: ']
player_2 = raw_input['Enter player 2 name: ']
current_space1 = 0
current_space2 = 0

# ...

def roll1[]:
    global current_space1  # instead of current_space1 = int[]
    # rest of the function ...

def roll2[]:
    global current_space2  # instead of current_space2 = int[]
    # rest of the function ...

Phải nói rằng, sử dụng biến toàn cầu không được coi là một thực tiễn tốt. Ví dụ, xem bài viết này và câu trả lời của nó.

Đã trả lời ngày 5 tháng 5 năm 2017 lúc 22:28May 5, 2017 at 22:28

MbydmbydMByD

Huy hiệu vàng 134K2626 gold badges264 silver badges274 bronze badges

current_space1current_space2 là các biến cục bộ của các hàm roll_1roll_2 tương ứng. Các biến đó thực sự được tăng lên bởi dòng

finish_line = 20
player_1 = raw_input['Enter player 1 name: ']
player_2 = raw_input['Enter player 2 name: ']
current_space1 = 0
current_space2 = 0

# ...

def roll1[]:
    global current_space1  # instead of current_space1 = int[]
    # rest of the function ...

def roll2[]:
    global current_space2  # instead of current_space2 = int[]
    # rest of the function ...
0 nhưng trong dòng tiếp theo, bạn đang gọi hàm một lần nữa có phạm vi riêng của nó trong đó
finish_line = 20
player_1 = raw_input['Enter player 1 name: ']
player_2 = raw_input['Enter player 2 name: ']
current_space1 = 0
current_space2 = 0

# ...

def roll1[]:
    global current_space1  # instead of current_space1 = int[]
    # rest of the function ...

def roll2[]:
    global current_space2  # instead of current_space2 = int[]
    # rest of the function ...
1 là 0 lúc bắt đầu. Điều này sẽ tiếp tục cho đến khi bạn đạt đến mức tối đa. Độ sâu đệ quy.

Thay vào đó, bạn có thể tạo các biến đó

finish_line = 20
player_1 = raw_input['Enter player 1 name: ']
player_2 = raw_input['Enter player 2 name: ']
current_space1 = 0
current_space2 = 0

# ...

def roll1[]:
    global current_space1  # instead of current_space1 = int[]
    # rest of the function ...

def roll2[]:
    global current_space2  # instead of current_space2 = int[]
    # rest of the function ...
2 và đánh dấu chúng như vậy với từ khóa
finish_line = 20
player_1 = raw_input['Enter player 1 name: ']
player_2 = raw_input['Enter player 2 name: ']
current_space1 = 0
current_space2 = 0

# ...

def roll1[]:
    global current_space1  # instead of current_space1 = int[]
    # rest of the function ...

def roll2[]:
    global current_space2  # instead of current_space2 = int[]
    # rest of the function ...
2.

Một cách tiếp cận khác là tạo ra một lớp

finish_line = 20
player_1 = raw_input['Enter player 1 name: ']
player_2 = raw_input['Enter player 2 name: ']
current_space1 = 0
current_space2 = 0

# ...

def roll1[]:
    global current_space1  # instead of current_space1 = int[]
    # rest of the function ...

def roll2[]:
    global current_space2  # instead of current_space2 = int[]
    # rest of the function ...
4

class Player:
    def __init__[self]:
        self.current_space = 0

và chỉ sử dụng một hàm

finish_line = 20
player_1 = raw_input['Enter player 1 name: ']
player_2 = raw_input['Enter player 2 name: ']
current_space1 = 0
current_space2 = 0

# ...

def roll1[]:
    global current_space1  # instead of current_space1 = int[]
    # rest of the function ...

def roll2[]:
    global current_space2  # instead of current_space2 = int[]
    # rest of the function ...
5 cùng với hai trường hợp
finish_line = 20
player_1 = raw_input['Enter player 1 name: ']
player_2 = raw_input['Enter player 2 name: ']
current_space1 = 0
current_space2 = 0

# ...

def roll1[]:
    global current_space1  # instead of current_space1 = int[]
    # rest of the function ...

def roll2[]:
    global current_space2  # instead of current_space2 = int[]
    # rest of the function ...
4 được truyền dưới dạng đối số cho hàm
finish_line = 20
player_1 = raw_input['Enter player 1 name: ']
player_2 = raw_input['Enter player 2 name: ']
current_space1 = 0
current_space2 = 0

# ...

def roll1[]:
    global current_space1  # instead of current_space1 = int[]
    # rest of the function ...

def roll2[]:
    global current_space2  # instead of current_space2 = int[]
    # rest of the function ...
5 đó. Sau đó, bạn sẽ tăng
finish_line = 20
player_1 = raw_input['Enter player 1 name: ']
player_2 = raw_input['Enter player 2 name: ']
current_space1 = 0
current_space2 = 0

# ...

def roll1[]:
    global current_space1  # instead of current_space1 = int[]
    # rest of the function ...

def roll2[]:
    global current_space2  # instead of current_space2 = int[]
    # rest of the function ...
8.

Ví dụ:

def roll[active_player, passive_player]:
    ...
    if active_player.current_space != finish_line:
        active_player.current_space += rolled_dice
        roll[passive_player, active_player]

BTW, bạn cũng có thể muốn suy nghĩ lại khi bạn kiểm tra người chơi đã đạt được mục tiêu vì trong ví dụ của bạn trước tiên bạn yêu cầu lăn và sau đó người chơi có thể giành chiến thắng từ một điểm số đã đạt được trước đó.

Đã trả lời ngày 5 tháng 5 năm 2017 lúc 22:28May 5, 2017 at 22:28

a_guesta_guesta_guest

Mbydmbyd10 gold badges57 silver badges108 bronze badges

0

Bạn có thể thay đổi một biến trong một câu lệnh if python?

Bạn không thể; không phải với cấu trúc if..elif. Python chọn điều kiện đầu tiên phù hợp và sẽ coi thường phần còn lại, bất kể bạn thực hiện thay đổi nào trong khối mã được chạy. elif structure. Python picks the first condition that matches and will disregard the rest, no matter what changes you make in the block of code that was run.

Bạn có thể đặt một biến trong một câu lệnh IF?

Nếu bạn chưa quen với cú pháp được sử dụng trong mẫu mã, nếu [int i = 5] {là một cách hoàn toàn hợp lệ để khai báo và xác định một biến, thì hãy sử dụng nó bên trong câu lệnh IF đã cho. Nó cho phép chúng tôi viết mã terser, rõ ràng hơn, đồng thời tránh giới hạn phạm vi của một biến.if [int i = 5] { is a perfectly valid way of declaring and defining a variable, then using it inside the given if statement. It allows us to write terser, clearer code, while also avoiding limiting the scope of a variable.

Bạn có thể tạo một biến bên trong một câu lệnh if python không?

Python cho phép tạo các biến trong một nếu ... Elif ... khác ... mệnh đề, để chúng có thể được sử dụng ngoài khối có điều kiện.Điều này cũng đúng cho các điều kiện lồng nhau. elif... else... clause, so that they can be used also outside the conditional block. This is also true for nested conditionals.

Bạn có thể sửa đổi một biến trong Python không?

Một số giá trị trong Python có thể được sửa đổi, và một số không thể.Điều này không bao giờ có nghĩa là chúng ta không thể thay đổi giá trị của một biến - nhưng nếu một biến chứa một giá trị của một loại bất biến, chúng ta chỉ có thể gán cho nó một giá trị mới.Chúng ta không thể thay đổi giá trị hiện có theo bất kỳ cách nào.. This does not ever mean that we can't change the value of a variable – but if a variable contains a value of an immutable type, we can only assign it a new value. We cannot alter the existing value in any way.

Bài Viết Liên Quan

Chủ Đề