【问题标题】:NameError -- not definied [closed]NameError——未定义[关闭]
【发布时间】:2011-07-01 03:13:31
【问题描述】:

主程序

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

第二个文件:wining.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

我已经尝试过引号和所有方法,但无法解决这个问题!!!有什么帮助吗? 请,谢谢!

【问题讨论】:

  • 请提供连贯的信息。回溯与代码没有任何共同之处……再说一次:我们没有做你的功课
  • @Alli Err... "ROCK = r" 不在您发布的代码中。请发布实际损坏的代码。正如所发布的,它应该运行良好,因为它将 ROCK 设置为 1。
  • 不要求任何人做我的作业。我只是寻求帮助学习。我深表歉意,不会再使用本网站寻求帮助,请理解我做错了什么......谢谢您,给您带来的不便深表歉意。
  • @Alli:您发布的代码不会产生您发布的错误。
  • @Alli!你也必须定义lose!您必须定义您使用的每个变量名称

标签: python variables definition nameerror


【解决方案1】:

不要以错误的方式使用否定的 cmets。请务必将您的作业标记为作业,并确保粘贴您发布的代码生成的实际错误。此错误与您发布的代码不匹配。

你也可以用一种看起来稍微平静的方式问你的问题:)

问题很简单。您在主程序中定义全局变量,但不在 winning.py 中定义,所以像

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

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

我会告诉你,你还必须 return 一个来自 winning.winner 的值,这会为你省去一些麻烦——否则,你将不会得到你期望的输出。

【讨论】:

  • 非常感谢!!从现在开始,我会确保所有帮助的标题中都有“作业”。
  • 谢谢你 Senderle...你很有帮助。
猜你喜欢
  • 2021-06-05
  • 2021-08-23
  • 2016-12-20
  • 2023-03-05
  • 2020-12-23
  • 2014-03-18
  • 2021-07-27
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多