首页 > 解决方案 > 任何人都知道如何编辑全局变量python?

问题描述

我将repl.it用于我的所有编码,并在下面放置了一个链接到这个问题所在的那个。 https://repl.it/@harrisoncopp/LoginRegister-Test-messy-code

我正在尝试编写一个更高/更低的游戏,用户猜测下一个数字是否会高于上一个。

我在下面放了一些代码,但如果你去 repl 并检查它可能更有意义。

分数在用户登录时在其他地方定义,当它从文件中提取他们的分数时 - 并将其转换为变量。

然后gameMenu()显示该人有多少硬币(分数)。

如果用户在 中猜对了playGame(),我希望它对硬币 +1。

然后我希望在gameMenu()脚本“传输”它们回来时显示新的硬币变量。

我知道这一切似乎很难解释,如果你检查 repl 可能会更容易。

但是我尝试这样做时遇到的错误int(score+1)是:

TypeError: can only concatenate str (not "int") to str

# Game section
def playGame():
  clear()
  print("===== Higher or Lower =====")
  global score
  print("Coins = ", score)
  print("\n")
  number1 = random.randint(0, 1000)
  number2 = random.randint(0, 1000)
  print("First Number: ", number1)
  print("\nWill the next number be [H]igher or [L]ower?")
  x = input("> ")
  if x == "H":
    if number1 < number2:
      print("Correct!")
      sleep(1)
      int(score+1)
      gameMenu()
    else:
      sleep(1)
      print("Sorry! You were wrong.")
      gameMenu()
  elif x == "L":
    if number1 > number2:
      print("Correct.")
      sleep(1)
      int(score+1)
      gameMenu()
    else:
      print("Sorry! You were wrong.")
      sleep(1)
      gameMenu()
  else:
    print("Option not recognised, going back to game menu.")
    sleep(1)
    gameMenu()

# Shows user the main game menu.
def gameMenu():
  clear()
  print("===== Higher or Lower =====")
  print("Coins = ", score)
  print("\n")
  print("(1) Play Round")
  print("(2) See Tutorial")
  print("(3) Save score")
  x = input("> ")
  if x == "1":
    playGame()
  elif x == "2":
    tutorial()
  elif x == "3":
    savescore()

标签: python

解决方案


但是我在尝试执行 int(score+1) 时遇到的错误是:

TypeError:只能将str(不是“int”)连接到str

该错误告诉我您正在尝试将 a 添加strint. 既然1是一个int,那就意味着score必须是一个str。您想在尝试向其添加 1int 之前将其变为 an ,而不是之后:

int(score) + 1

推荐阅读