Hướng dẫn global variable not updating python - biến toàn cục không cập nhật python

Tôi mới với Python và lập trình nhưng dường như tôi không thể hiểu tại sao chức năng này không cập nhật biến toàn cầu

global weight
weight = 'value'
def GetLiveWeight():
    SetPort()
    while interupt == False:
        port.write(requestChar2)
        liveRaw = port.read(9)
        liveRaw += port.read(port.inWaiting())
        time.sleep(0.2)
        weight = liveRaw.translate(None, string.letters)
    return weight

Tôi cũng đã thử điều này:

weight = 'value'
def GetLiveWeight():
    global weight
    SetPort()
    while interupt == False:
        port.write(requestChar2)
        liveRaw = port.read(9)
        liveRaw += port.read(port.inWaiting())
        time.sleep(0.2)
        weight = liveRaw.translate(None, string.letters)
    return weight

try:
    threading.Thread(target = GetLiveWeight).start()
    print liveWeight
except:
    print "Error: unable to start thread"

Hướng dẫn global variable not updating python - biến toàn cục không cập nhật python

Hdjemai

9.16945 Huy hiệu vàng69 Huy hiệu bạc89 Huy hiệu Đồng45 gold badges69 silver badges89 bronze badges

hỏi ngày 28 tháng 7 năm 2013 lúc 19:09Jul 28, 2013 at 19:09

Bạn cần phải tuyên bố rằng weight là toàn cầu bên trong ____10, không phải bên ngoài nó.

weight = 'value'
def GetLiveWeight():
    global weight

Tuyên bố

weight = 'value'
def GetLiveWeight():
    global weight
    SetPort()
    while interupt == False:
        port.write(requestChar2)
        liveRaw = port.read(9)
        liveRaw += port.read(port.inWaiting())
        time.sleep(0.2)
        weight = liveRaw.translate(None, string.letters)
    return weight

try:
    threading.Thread(target = GetLiveWeight).start()
    print liveWeight
except:
    print "Error: unable to start thread"
1 nói với Python rằng trong phạm vi của hàm
weight = 'value'
def GetLiveWeight():
    global weight
    SetPort()
    while interupt == False:
        port.write(requestChar2)
        liveRaw = port.read(9)
        liveRaw += port.read(port.inWaiting())
        time.sleep(0.2)
        weight = liveRaw.translate(None, string.letters)
    return weight

try:
    threading.Thread(target = GetLiveWeight).start()
    print liveWeight
except:
    print "Error: unable to start thread"
0, weight đề cập đến biến toàn cầu weight, chứ không phải một số biến cục bộ mới weight.

Đã trả lời ngày 28 tháng 7 năm 2013 lúc 19:10Jul 28, 2013 at 19:10

UnutbuUnutbuunutbu

803K173 Huy hiệu vàng1724 Huy hiệu bạc1626 Huy hiệu đồng173 gold badges1724 silver badges1626 bronze badges

4

Tại sao các biến toàn cầu nên tránh trong Python?

Mặc dù trong nhiều hoặc hầu hết các biến ngôn ngữ lập trình khác được coi là toàn cầu nếu không được tuyên bố khác, Python liên quan đến các biến theo cách khác. Họ là địa phương, nếu không tuyên bố. Lý do lái xe đằng sau phương pháp này là các biến toàn cầu nói chung là thực tiễn xấu và nên tránh.

def create_summary():
    file_list = glob.glob('*.log')
    for i in file_list:
        global comp_line      # GLOBAL HERE
        comp_line = 0         #
        print(comp_line)      # PRINT1
        with open(i, 'r') as cur_file:
            cur_lines = cur_file.readlines()
            for line in cur_lines:
                if 'IS BLANK' in line:
                    blank(i, line)
                elif 'POTENTIAL ERROR (2)' in line:
                    err2(i, line)
                elif 'ERROR (3)' in line:
                    err3(i, line)
                elif 'STATUS: OK' in line:
                    stat(i, line)

Tôi xác định biến của mình chỉ dưới hàng nhập khẩu của mình.

def blank(fname, line):
    global comp_line                       # GLOBAL HERE
    with open('blank.tmp', 'r') as f:
        fline_read = f.readlines()
    wline = f'=== {fname} ==='
    for line1 in fline_read:
        if comp_line >= 1:                 #
            print(comp_line)               #PRINT2
        else:
            with open('blank.tmp', 'a') as f:
                print('New wline')
                f.writelines('\n' + wline + '\n')
                comp_line += 1             #
    with open('blank.tmp', 'a') as f:
        f.writelines(line)

weight = 'value'
def GetLiveWeight():
    global weight
    SetPort()
    while interupt == False:
        port.write(requestChar2)
        liveRaw = port.read(9)
        liveRaw += port.read(port.inWaiting())
        time.sleep(0.2)
        weight = liveRaw.translate(None, string.letters)
    return weight

try:
    threading.Thread(target = GetLiveWeight).start()
    print liveWeight
except:
    print "Error: unable to start thread"
6. Sau đó tôi cần điều này trong một chức năng bên dưới (nhận xét bên cạnh biến):

file12020-09-14.log
0
New wline
1
1
1
1
1
1
1
1
1
file22020-09-14.log
0
1

Sau đó tôi cũng cần điều này trong

weight = 'value'
def GetLiveWeight():
    global weight
    SetPort()
    while interupt == False:
        port.write(requestChar2)
        liveRaw = port.read(9)
        liveRaw += port.read(port.inWaiting())
        time.sleep(0.2)
        weight = liveRaw.translate(None, string.letters)
    return weight

try:
    threading.Thread(target = GetLiveWeight).start()
    print liveWeight
except:
    print "Error: unable to start thread"
7,
weight = 'value'
def GetLiveWeight():
    global weight
    SetPort()
    while interupt == False:
        port.write(requestChar2)
        liveRaw = port.read(9)
        liveRaw += port.read(port.inWaiting())
        time.sleep(0.2)
        weight = liveRaw.translate(None, string.letters)
    return weight

try:
    threading.Thread(target = GetLiveWeight).start()
    print liveWeight
except:
    print "Error: unable to start thread"
8,
weight = 'value'
def GetLiveWeight():
    global weight
    SetPort()
    while interupt == False:
        port.write(requestChar2)
        liveRaw = port.read(9)
        liveRaw += port.read(port.inWaiting())
        time.sleep(0.2)
        weight = liveRaw.translate(None, string.letters)
    return weight

try:
    threading.Thread(target = GetLiveWeight).start()
    print liveWeight
except:
    print "Error: unable to start thread"
9,
weight = 'value'
def GetLiveWeight():
    global weight
0. Các chức năng này gần giống hệt nhau, vì vậy đây là trống (một lần nữa, nhận xét nơi sử dụng biến được sử dụng)after a new file is loaded (print1)

Ở trên, tôi đã thêm các câu lệnh in để xem những gì đang diễn ra. Đây là đầu ra:

Tôi đang làm một máy đánh bạc và tôi không có kinh nghiệm trong mã hóa. Tôi đang đấu tranh để có được biến tiền để cập nhật khi tôi đạt được hoặc mất bất kỳ. Tôi không chắc chắn liệu nó chỉ là đầu ra của nó hay biến thực tế. Đây là mã của tôi:

import tkinter as tk
import random
#I added an extra item
#Check line 37

print("Welcome to the Virtual Slot Machine")
global coins
coins = 100
symbols = ["bell", "cherry", "banana", "dollar", "skull"]
done = False

def sort(lists):
  for i in range(len(lists)-1):
    for x in range(len(lists)-1-i):
      if lists[x] < lists[x + 1]:
        lists[x], lists[x + 1] = lists[x + 1], lists[x]

  return lists

def open_file():
  f = open("highscores.txt","r")
  line = f.readlines()
  f.close()
  list1 = [int(i) for i in line[0].split(",")]
  ordered = sort(list1)
  return ordered
  
print("The highscores so far from higherst to smallest are: ")
print(*open_file())

def turn(coins):
  coins -= 5
  fruit = ["cherry", "banana"]
  slot1 = random.choice(symbols)
  slot2 = random.choice(symbols)
  slot3 = random.choice(symbols)
  if random.randint(0,10000) == 1:
    slot3 = "Gold Bar"
  slots = [slot1,slot2,slot3]
  print("You got {} {} {}".format(slot1,slot2,slot3))

  if "skull" not in slots:
    if (slot1 and slot2 and slot3) == "dollar":
      print("You got 3 dollars! +500 coins")
      coins += 500
    elif (slot1 and slot2) or (slot1 and slot3) or (slot2 and slot3) == "dollar":
      print("You got 2 dollars! +50 coins")
      coins += 50
    elif "dollar" in slots:
      print("You got 1 dollar! + 1 coin")
      coins += 1
    if (slot1 and slot2 and slot3) in fruit:
      print("You got 3 fruit! +50 coins!")
      coins += 50
    elif ((slot1 and slot2) or (slot1 and slot3) or (slot2 and slot3) in fruit) and (slot1 == slot2) or (slot1 == slot3) or (slot2 == slot3):
      print("You got 2 of the same fruit! +10 coins")
    if (slot1 and slot2 and slot3) == "bell":
      print("You got 3 bells! +1000 coins!")
      coins += 1000
    elif (slot1 and slot2) or (slot1 and slot3) or (slot2 and slot3) == "bell":
      print("You got 2 bells! +100 coins")
  else:
    print("Unlucky, you got a skull, you lose!")
  if slot3 == "Gold Bar":
    print("Jackpot! All coins times 10!")
    coins = coins*10

while coins > 0 and done == False:
  print("You have {0} coins".format(coins))
  play = input("Do you want to play a round? It costs 5 coins? y/n ")
  coins_left = coins - 5
  if play == "y" and coins_left > 0:
    turn(coins)
  else:
    if coins_left < 0:
      print("Sorry, you do not havwe enough money")
      print("You ended with {0} coins".format(coins))
    else:
      print("Ok, thanks for playing")
      print("You ended with {0} coins!".format(coins))
      done = True

Bài viết: 481481

Chủ đề: 8686

Tham gia: Tháng 2 năm 2018Feb 2018

Danh tiếng: 21 21

MAR-29-2020, 01:33 AM (Bài đăng này đã được sửa đổi lần cuối: Mar-29-2020, 01:57 AM bởi Sheepposu.) (This post was last modified: Mar-29-2020, 01:57 AM by SheeppOSU.)

Khi bạn lần đầu tiên bắt đầu các đồng tiền biến, đó là một biến công khai để nói trên toàn bộ chương trình, ngoại trừ trong các lớp và chức năng. Hàm, khi được thực thi, tạo biến số tiền riêng của mình. Bây giờ bạn có thể sử dụng các biến toàn cầu, tuy nhiên, nhiều người không khuyến nghị điều đó. Thay vào đó, sử dụng chức năng trả về như vậy. (Kiểm tra dòng 67 và 74).

import tkinter as tk
import random
#I added an extra item
#Check line 37
 
print("Welcome to the Virtual Slot Machine")
global coins
coins = 100
symbols = ["bell", "cherry", "banana", "dollar", "skull"]
done = False
 
def sort(lists):
  for i in range(len(lists)-1):
    for x in range(len(lists)-1-i):
      if lists[x] < lists[x + 1]:
        lists[x], lists[x + 1] = lists[x + 1], lists[x]
 
  return lists
 
def open_file():
  f = open("highscores.txt","r")
  line = f.readlines()
  f.close()
  list1 = [int(i) for i in line[0].split(",")]
  ordered = sort(list1)
  return ordered
   
print("The highscores so far from higherst to smallest are: ")
print(*open_file())
 
def turn(coins):
  coins -= 5
  fruit = ["cherry", "banana"]
  slot1 = random.choice(symbols)
  slot2 = random.choice(symbols)
  slot3 = random.choice(symbols)
  if random.randint(0,10000) == 1:
    slot3 = "Gold Bar"
  slots = [slot1,slot2,slot3]
  print("You got {} {} {}".format(slot1,slot2,slot3))
 
  if "skull" not in slots:
    if (slot1 and slot2 and slot3) == "dollar":
      print("You got 3 dollars! +500 coins")
      coins += 500
    elif (slot1 and slot2) or (slot1 and slot3) or (slot2 and slot3) == "dollar":
      print("You got 2 dollars! +50 coins")
      coins += 50
    elif "dollar" in slots:
      print("You got 1 dollar! + 1 coin")
      coins += 1
    if (slot1 and slot2 and slot3) in fruit:
      print("You got 3 fruit! +50 coins!")
      coins += 50
    elif ((slot1 and slot2) or (slot1 and slot3) or (slot2 and slot3) in fruit) and (slot1 == slot2) or (slot1 == slot3) or (slot2 == slot3):
      print("You got 2 of the same fruit! +10 coins")
    if (slot1 and slot2 and slot3) == "bell":
      print("You got 3 bells! +1000 coins!")
      coins += 1000
    elif (slot1 and slot2) or (slot1 and slot3) or (slot2 and slot3) == "bell":
      print("You got 2 bells! +100 coins")
  else:
    print("Unlucky, you got a skull, you lose!")
  if slot3 == "Gold Bar":
    print("Jackpot! All coins times 10!")
    coins = coins*10
  return coins
 
while coins > 0 and done == False:
  print("You have {0} coins".format(coins))
  play = input("Do you want to play a round? It costs 5 coins? y/n ")
  coins_left = coins - 5
  if play == "y" and coins_left > 0:
    coins = turn(coins)
  else:
    if coins_left < 0:
      print("Sorry, you do not havwe enough money")
      print("You ended with {0} coins".format(coins))
    else:
      print("Ok, thanks for playing")
      print("You ended with {0} coins!".format(coins))
      done = True

Tôi cũng muốn chỉ ra rằng mã của bạn hơi lộn xộn. Từ điển thường có thể rất hữu ích trong mã gọn gàng và rút ngắn nó. Tôi đã áp dụng điều này cho chức năng rẽ chính của bạn. Nếu bạn học cách làm việc với các từ điển như thế này, nó sẽ rất hữu ích trong tương lai. Tôi đề nghị rằng một khi bạn hoàn thành nó, bạn sẽ làm sạch nó một chút với điều này. Bạn cũng có thể sử dụng thời gian. Ngủ từ thư viện thời gian

weight = 'value'
def GetLiveWeight():
    global weight
2 và sử dụng nó ở giữa một số thứ nhất định để không phải mọi thứ chỉ được in cùng một lúc.

import tkinter as tk
import random
#I added an extra item
#Check line 37
 
print("Welcome to the Virtual Slot Machine")
global coins
coins = 100
symbols = ["bells", "cherries", "bananas", "dollars", "skull"]
done = False
 
def sort(lists):
  for i in range(len(lists)-1):
    for x in range(len(lists)-1-i):
      if lists[x] < lists[x + 1]:
        lists[x], lists[x + 1] = lists[x + 1], lists[x]
 
  return lists
 
def open_file():
  f = open("highscores.txt","r")
  line = f.readlines()
  f.close()
  list1 = [int(i) for i in line[0].split(",")]
  ordered = sort(list1)
  return ordered
   
print("The highscores so far from higherst to smallest are: ")
print(*open_file())

def Match(slot1, slot2, slot3):
  if slot1 == slot2 and slot2 == slot3:
    return slot1, 1
  if slot1 == slot2:
    return slot1, 0
  if slot2 == slot3:
    return slot2, 0
  if slot1 == slot3:
    return slot3, 0
  return None, None
 
def turn(coins):
  coins -= 5
  fruits = ["cherries", "bananas"]
  slot1 = random.choice(symbols)
  slot2 = random.choice(symbols)
  slot3 = random.choice(symbols)
  slots = [slot1, slot2, slot3]
  RewardDict = {"dollars" : [50, 500], "bells": {100, 1000}}
  for fruit in fruits:
      RewardDict.update({fruit: [10, 50]})
      
  if random.randint(0,10000) == 1:
    slot3 = "Gold Bar"

  print("You got {} {} {}".format(slot1,slot2,slot3))
 
  if "skull" not in slots:
    match, number = Match(slot1, slot2, slot3)
    if match != None:
      coins += RewardDict[match][number-1]
      print("You got {} {}! +{} coins!".format(number+2, match, RewardDict[match][number]))

  else:
    print("Unlucky, you got a skull, you lose!")
    
  if slot3 == "Gold Bar":
    print("Jackpot! All coins times 10!")
    coins = coins*10
  return coins
 
while coins > 0 and done == False:
  print("You have {0} coins".format(coins))
  play = input("Do you want to play a round? It costs 5 coins? y/n ")
  coins_left = coins - 5
  if play == "y" and coins_left > 0:
    coins = turn(coins)
  else:
    if coins_left < 0:
      print("Sorry, you do not havwe enough money")
      print("You ended with {0} coins".format(coins))
    else:
      print("Ok, thanks for playing")
      print("You ended with {0} coins!".format(coins))
      done = True

Lập trình viên Rayaan tên là Tim
Programmer named Tim

Bài viết: 77

Chủ đề: 66

Tham gia: tháng 8 năm 2019Aug 2019

Danh tiếng: 0 0

MAR-29-2020, 12:51 PM (Bài đăng này đã được sửa đổi lần cuối: Mar-29-2020, 01:08 PM của Rayaan.) (This post was last modified: Mar-29-2020, 01:08 PM by Rayaan.)

.SheeppOSU Wrote: if "skull" not in slots:
match, number = Match(slot1, slot2, slot3)

Xin lỗi nếu đây là một câu hỏi đơn giản nhưng dấu phẩy làm gì giữa trận đấu và số?

. Nếu slot2 == slot3: return slot2, 0 if slot1 == slot3: return slot3, 0 return none, noneSheeppOSU Wrote: def Match(slot1, slot2, slot3):
if slot1 == slot2 and slot2 == slot3:
return slot1, 1
if slot1 == slot2:
return slot1, 0
if slot2 == slot3:
return slot2, 0
if slot1 == slot3:
return slot3, 0
return None, None

Ngoài ra, không nên tất cả các IF khác ngoài ELIF đầu tiên để nó không có nhiều đầu ra?

Cảm ơn sự giúp đỡ, tôi sẽ cố gắng sử dụng từ điển nhiều hơn


. Nếu slot2 == slot3: return slot2, 0 if slot1 == slot3: return slot3, 0 return none, noneSheeppOSU Wrote: def Match(slot1, slot2, slot3):
if slot1 == slot2 and slot2 == slot3:
return slot1, 1
if slot1 == slot2:
return slot1, 0
if slot2 == slot3:
return slot2, 0
if slot1 == slot3:
return slot3, 0
return None, None

Ngoài ra, không nên tất cả các IF khác ngoài ELIF đầu tiên để nó không có nhiều đầu ra?

Bài viết: 481481

Chủ đề: 8686

Tham gia: Tháng 2 năm 2018Feb 2018

Danh tiếng: 21 21

MAR-29-2020, 01:33 AM (Bài đăng này đã được sửa đổi lần cuối: Mar-29-2020, 01:57 AM bởi Sheepposu.) (This post was last modified: Mar-29-2020, 04:42 PM by SheeppOSU.)

Khi bạn lần đầu tiên bắt đầu các đồng tiền biến, đó là một biến công khai để nói trên toàn bộ chương trình, ngoại trừ trong các lớp và chức năng. Hàm, khi được thực thi, tạo biến số tiền riêng của mình. Bây giờ bạn có thể sử dụng các biến toàn cầu, tuy nhiên, nhiều người không khuyến nghị điều đó. Thay vào đó, sử dụng chức năng trả về như vậy. (Kiểm tra dòng 67 và 74).Rayaan Wrote: Sorry, I was just reading through and I realised I do not know how this works. If you could explain that would be very helpful thanks. I just don't know how returning None, None gives anything or what it does.

Tôi cũng muốn chỉ ra rằng mã của bạn hơi lộn xộn. Từ điển thường có thể rất hữu ích trong mã gọn gàng và rút ngắn nó. Tôi đã áp dụng điều này cho chức năng rẽ chính của bạn. Nếu bạn học cách làm việc với các từ điển như thế này, nó sẽ rất hữu ích trong tương lai. Tôi đề nghị rằng một khi bạn hoàn thành nó, bạn sẽ làm sạch nó một chút với điều này. Bạn cũng có thể sử dụng thời gian. Ngủ từ thư viện thời gian

weight = 'value'
def GetLiveWeight():
    global weight
2 và sử dụng nó ở giữa một số thứ nhất định để không phải mọi thứ chỉ được in cùng một lúc.

Tại sao biến không cập nhật trong Python?

Nếu bạn cố gắng cập nhật một biến không tồn tại, bạn sẽ gặp lỗi vì Python đánh giá biểu thức ở phía bên phải của toán tử gán trước khi nó gán giá trị kết quả cho tên bên trái. Trước khi bạn có thể cập nhật một biến, bạn phải khởi tạo nó, thường là với một bài tập đơn giản.Python evaluates the expression on the right side of the assignment operator before it assigns the resulting value to the name on the left. Before you can update a variable, you have to initialize it, usually with a simple assignment.

Bạn có thể cập nhật một biến toàn cầu trong Python không?

Trong Python, từ khóa toàn cầu cho phép bạn sửa đổi biến bên ngoài phạm vi hiện tại.Nó được sử dụng để tạo ra một biến toàn cầu và thay đổi biến trong bối cảnh cục bộ.global keyword allows you to modify the variable outside of the current scope. It is used to create a global variable and make changes to the variable in a local context.

Bạn có thể cập nhật một biến toàn cầu không?

Các chức năng có thể truy cập các biến toàn cầu và sửa đổi chúng.Sửa đổi các biến toàn cầu trong một hàm được coi là thực hành lập trình kém.Tốt hơn là gửi một biến trong một tham số (hoặc có nó được trả về trong câu lệnh 'return').. Modifying global variables in a function is considered poor programming practice. It is better to send a variable in as a parameter (or have it be returned in the 'return' statement).

Tại sao các biến toàn cầu nên tránh trong Python?

Mặc dù trong nhiều hoặc hầu hết các biến ngôn ngữ lập trình khác được coi là toàn cầu nếu không được tuyên bố khác, Python liên quan đến các biến theo cách khác.Họ là địa phương, nếu không tuyên bố.Lý do lái xe đằng sau phương pháp này là các biến toàn cầu nói chung là thực tiễn xấu và nên tránh.global variables are generally bad practice and should be avoided.