首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >全局变量未更新

全局变量未更新
EN

Stack Overflow用户
提问于 2022-02-28 06:20:14
回答 2查看 50关注 0票数 0
代码语言:javascript
复制
answer_B = ["B", "b"]
answer_C = ["C", "c"]
def tool1():
  global tool
  tool = 1
def ore1():
  global ore
  ore = 1
def cave():
  ore = 0
  tool = 0
  while True:
    print("\nYou walk inside the clocktower, looking all around and you see 3 rooms. \n Room A fulled with ORE \n Room B which has a Smelter \n Room C walled off with rocks")
    choice3 = input(">>")
    if choice3 in answer_A:
      print("You grab the ore and walk observe the rooms \n +1 ore")
      ore1()
      print(ore)
    elif choice3 in answer_B:
      if ore == 1:
        print("You use the ore and smelt it into iron chunks, and you craft an iron pickaxe \n + Iron Tool")
        tool1()
        print(tool)
      elif ore == 0:
        print("You walk inside, and observe the smelter with coal inside, Maybe you can smelt some sort of ore and make an tool?")
    elif choice3 in answer_C:
      if tool == 0 and ore == 0:
        print("You observe thde wall walled off with rocks, Maybe you could smelt ore and make a tool?")
      elif tool == 0 and ore == 1:
        print("You have the ore, You need to make it into a tool? Maybe the smelter room could help")
      elif tool == 1:
        print("You use the tool and break the wall")
         
    if tool1() == 1:
      print("You Did It!")
      break
cave()

为什么矿石没有更新到1当你做选择A?我把它变成了一个全局变量,但我不知道我还能做什么

(我刚接触到蟒蛇,如果这是个愚蠢的问题,我很抱歉)

EN

回答 2

Stack Overflow用户

发布于 2022-02-28 06:30:45

代码中有两个ore变量。一个是cave()函数中的局部函数,另一个是全局函数。当您调用ore1()函数时,全局变量将按预期更新为1,但在下一行中打印的ore变量是本地ore变量。要解决这个问题,您可以在ore函数的开头声明cave()变量全局,就像在'ore1()‘函数中那样

票数 0
EN

Stack Overflow用户

发布于 2022-02-28 06:30:52

与其这样做,不如:

  1. 在开始时声明工具和矿石本身,

代码语言:javascript
复制
`tool = 0`
代码语言:javascript
复制
 `ore = 0`

无论您在哪里写ore = 1

  1. 都用tool = 1代替ore1(),用tool = 1代替ore1()
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/71291253

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档