NameError - 未定义

时间:2011-07-01 03:13:32

标签: python variables definition nameerror

主程序

# import statements
import random
import winning

# Set constants
win = 0
lose = 0
tie = 0

ROCK = 1
PAPER = 2
SCISSOR = 3

# Main Program for the Rock Paper Scissor game.
def main():
    # set variable for loop control
    again = 'y'

    while again == 'y':
        # Display menu
        display_menu()
        # prompt for user input
        userSelection = input('Which would you like to play with (1, 2, 3)?: ') 
        computerSelection = random.randint(1, 3) 

        # Call winner module to decide the winner!
        print(winning.winner(userSelection, computerSelection))

        # Ask to play again and make selection
        again = input('Would you like to play again (y/n)?')


def display_menu():
    print('Please make a selection: ')
    print(' 1) Play Rock')
    print(' 2) Play Paper')
    print(' 3) Play Scissor')



# Call main
main()

第二档:winner.py:

# This module will decide on who won based on input from Main

def winner(userInput, computerInput):
    if userInput == ROCK and computerInput == SCISSOR:
        print('You win!  Rock crushes Scissor!')
        win += 1
    elif userInput == SCISSOR and computerInput == PAPER:
        print('You win!  Scissor cuts Paper!')
        win += 1
    elif userInput == PAPER and computerInput == ROCK:
        print('You win!  Paper covers Rock!')
        win += 1
    elif userInput == computerInput:
        print('You tied with the computer! Please try again!')
        tie += 1
    else:
        print('You lost! Please try again!')
        lose += 1

错误

Traceback (most recent call last):
  File "C:/Python32/RPS_Project/Main.py", line 14, in <module>
    ROCK = r
NameError: name 'r' is not defined

我已经尝试了所有的引号,并且无法弄清楚这个!!!对此有何帮助? 拜托,谢谢!

1 个答案:

答案 0 :(得分:2)

不要以错误的方式接受负面评论。请务必将作业标记为作业,并确保粘贴您发布的代码生成的实际错误。此错误与您发布的代码不符。

您也可能会以稍微平静的方式提出您的问题:)

问题很简单。你可以在主程序中定义你的全局变量而不是winning.py中的全局变量,所以像

这样的行
if userInput == ROCK and computerInput == SCISSOR:
    print('You win!  Rock crushes Scissor!')
    win += 1

会导致NameErrors,因为未定义ROCKSCISSORwin。在每个模块中,必须定义或导入您要使用的所有名称;名称不会自动在模块之间共享 - 这是有充分理由的!

通过告诉您还必须return来自winning.winner的值,我会省去一些麻烦 - 否则,您将无法获得预期的输出。