NameError -- 未定义

-2 投票
1 回答
1920 浏览
提问于 2025-04-16 20:38

主程序

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

第二个文件:winning.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 个回答

3

别把负面的评论想得太复杂。记得把你的作业标记为作业,并且一定要贴上你代码运行后出现的实际错误信息。因为你贴的错误和你发的代码不一致。

你也可以试着用更平和的语气来提问哦 :)

问题其实很简单。你在主程序里定义了全局变量,但在 winning.py 里没有定义,所以像下面这样的代码

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

会导致名称错误,因为 ROCKSCISSORwin 这些名字没有被定义。在每个模块里,你 必须 定义或者导入所有你想用的名字;名字在模块之间不会自动共享——这是有原因的!

我告诉你一个小窍门,你还需要从 winning.winner 返回一个值——否则,你得不到你期待的输出。

撰写回答