2016-05-05 46 views
0

這是一個我在repl.it中編寫的腳本程序,我將顯示我的大部分錯誤。當我嘗試這樣做:Python添加一個預先存在的變量

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,則在後臺它是= 2,然後是3,然後是4,ECT?

回答

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("> ")) 

Demo

相關問題