这是我在repl.it中制作的一个脚本程序。我将显示我的大部分错误。当我尝试这样做时:
words = ["worda", "wordb", "wordc", "wordd"]
def show_help():
print("Type one of the four words that person says into the input.")
print("Type the word you want to tally into the console. Note that the words are case sensitive")
print("Type HELP if you need this to show")
def main(inpt):
a = 0
b = 0
c = 0
d = 0
while True:
if inpt == 'worda':
a += 1
print("{} has spurt. It now has: {} spurts".format(inpt, a))
break
main(input("> "))
if inpt == 'wordb':
a += 1
print("{} has spurt. It now has: {} spurts".format(inpt, b))
break
main(input("> "))
show_help()
main(input("> "))
这里发生了什么,它只是说“Worda已经突然爆发。它现在有:1次喷射”它只是这样说。它没有增加我需要它计算的时间。
words = ["worda", "wordb", "wordc", "wordd"]
a = 1
b = 1
c = 1
d = 1
def show_help():
print("Type one of the four words that person says into the input.")
print("Type the word you want to tally into the console. Note that the words are case sensitive")
print("Type HELP if you need this to show.")
def main(inpt): #The main block that is causing errors.
while True:
if inpt == 'worda':
nonlocal a #what I think will make the program reach out to the variables
a += 1
print("{} has spurt. It now has: {} spurts".format(inpt, a))
break
if inpt == 'wordb':
nonlocal b #I get a syntax error here saying "no binding for nonlocal 'b' found"
b += 1
print("{} has spurt. It now has: {} spurts".format(inpt, b))
break
main(input("> "))
show_help()
main(input("> "))
如何修复此问题并将其添加为:a + = 1,然后在后台它是a = 2,然后是3,然后是4,等等?
答案 0 :(得分:1)
您需要global
关键字才能访问它们:
words = ["worda", "wordb", "wordc", "wordd"]
a = 1
b = 1
c = 1
d = 1
def show_help():
print("Type one of the four words that person says into the input.")
print("Type the word you want to tally into the console. Note that the words are case sensitive")
print("Type HELP if you need this to show.")
def main(inpt): # The main block that is causing errors.
while True:
if inpt == 'worda':
global a
a += 1
print("{} has spurt. It now has: {} spurts".format(inpt, a))
break
if inpt == 'wordb':
global b
b += 1
print("{} has spurt. It now has: {} spurts".format(inpt, b))
break
main(input("> "))
show_help()
main(input("> "))