python - 任何人都知道如何编辑全局变量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()
解决方案
但是我在尝试执行 int(score+1) 时遇到的错误是:
TypeError:只能将str(不是“int”)连接到str
该错误告诉我您正在尝试将 a 添加str
到int
. 既然1
是一个int
,那就意味着score
必须是一个str
。您想在尝试向其添加 1int
之前将其变为 an ,而不是之后:
int(score) + 1
推荐阅读
- sql - SQL中如何同时计数和分组?(北风)
- macos - MacOS BigSur cmake“找不到 ZLIB”
- python - Virtualenv,它保存在哪里以及如何使用它(python,Windows 10)
- javascript - 循环变量或数组
- vim - 根据vim中的正则表达式更改折叠文本颜色?
- algorithm - 伪代码的摊销时间复杂度分析
- python - ModuleNotFoundError:jupyter 笔记本中没有名为“seaborn”的模块
- regex - 正则表达式捕捉两种不同的场景
- javascript - .setNumberFormat 在 Google Apps 脚本中不起作用
- mysql - SQL Inner Join 仅基于过滤记录的一行