[英]Anyone know how to edit a global variable python?
我將repl.it用於我的所有編碼,並在下面放置了一個鏈接到這個問題所在的那個。 https://repl.it/@harrisoncopp/LoginRegister-Test-messy-code
我正在嘗試編寫一個更高/更低的游戲,用戶猜測下一個數字是否會高於上一個。
我在下面放了一些代碼,但是如果您將 go 放入 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
該錯誤告訴我您正在嘗試將str
添加到int
。 由於1
是int
,這意味着score
必須是str
。 您想在嘗試向其添加 1之前將其轉換為int
,而不是之后:
int(score) + 1
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.