2016-03-06 65 views
1

我是一個新的Python編碼器,我想知道如何修復這個錯誤。每當我在代碼中輸入正確的輸入時,它都會發出錯誤消息,就像這樣。在Python 3.5.1中沒有定義的變量

代碼

total = 12 
print ("I will play a game, you will choose 1, 2, or 3, and I will do the same, and I should always win, do you want to play?") 
yesnoA = input("Yes or No?") 
if yesnoA == yes: 
    print ("Yay, your turn!") 
    turnAA = input('Your First Move') 
    if turnAA == 1: 
     print ("I choose 3") 
     total = total - 4 
     print ("Total = ",total) 
    else: 
     if turnAA == 2: 
      print ("I choose 2") 
      total = total - 4 
      print ("Total = ",total) 
     else: 
      if turnAA == 3: 
       print ("I choose 1") 
       total = total - 4 
       print ("Total = ",total) 
      else: 
       print ("Cheater, try again") 
else: 
    yesnoB = input("Ok, you sure?") 
    if yesnoB == yes: 
     print ("Yay, your turn") 
     turnAA = input('Your First Move') 
     if turnAA == 1: 
      print ("I choose 3") 
      total = total - 4 
      print ("Total = ",total) 
     else: 
      if turnAA == 2: 
       print ("I choose 2") 
       total = total - 4 
       print ("Total = ",total) 
      else: 
       if turnAA == 3: 
        print ("I choose 1") 
        total = total - 4 
        print ("Total = ",total) 
       else: 
        print ("Cheater, try again") 
    else: 
     print ("Well, goodbye") 

輸出

Yes or No?yes 
Traceback (most recent call last): 
    File "C:/Users/*user*/Desktop/Code/Python/Nim Game.py", line 5, in <module> 
    if yesnoA == yes: 
NameError: name 'yes' is not defined 

這是版本3.5.1

+0

你應該接受你認爲最有幫助的答案。接受答案也給你代表! –

回答

0

您正在嘗試比較yesnoA一個名爲yes變量,它確實是未定義,而不是字符串文字'yes'(注意引號!)。添加引號,您應該沒問題:

if yesnoA == 'yes': 
    # Here --^---^ 
1

您尚未定義變量yes。你應該這樣做:

yes = "Yes" 

在代碼

+0

不,我的意思是讓他定義變量,如果他想要的話,就像在C++中定義一個宏一樣。只是爲了讓他對字符串「yes」有個「常量」比較變量 – Mixone

2

您需要任何聲明一個變量yes用一個值'yes',或用繩子'yes'比較你的變量yesnoA的開始。也許是這樣的:

if yesnoA.lower() == 'yes': # using lower(), so that user's input is case insensitive 
    # do the rest of your work 

你的代碼事後有更多的問題。我會給你一個線索。 input始終以字符串的形式返回用戶的輸入。所以,如果你需要從用戶的整數,你將不得不使用用戶輸入轉換爲整數int(your_int_as_string)像這樣:

turnAA = int(input('Your First Move')) 
# turnAA is now an integer, provided the user entered valid integer value 

你拿這個問題上的SO:

  • 看那追溯。它明確說明錯誤出現在哪條線上,以及錯誤是什麼。你的情況是NameError
  • 看看文檔爲NameError
  • 研究this tutorial。它會幫助你習慣於遇到一些常見的基本錯誤。
+1

這比我提出的答案要好得多,忘記了'.lower()'方法哈哈 – Mixone