变量内容中的Python NameError [英] Python NameError from contents of a variable

查看:99
本文介绍了变量内容中的Python NameError的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在为Minecraft的Raspberry Pi版本制作一个mod,每次我在程序中输入一个命令时,都会遇到一个非常令人沮丧的错误.这是我的代码:

I've been making a mod for the Raspberry Pi version of Minecraft and I'm getting a very frustrating error every time I enter one of the commands in my program. Here's my code:

import minecraft.minecraft as minecraft
import minecraft.block as block
import time

mc = minecraft.Minecraft.create();

print('newBlock - Change ID of block to spawn')
print('blockType - Change subID of block to spawn')
print('pos1')
print('pos2')
print('fill - fill specified area')
print('clear - clear specified area')
print
while True:
comm=str(input('Command: '))
if comm=="newBlock":
    blockId = int(input('Enter Block ID: '))
    mc.postToChat('Block set to ID: ' + str(blockId))
if comm=="blockType":
    blockData = int(input('Enter Block Type: '))
if comm=="pos1":
    position1 = mc.player.getPos()
    mc.postToChat('Set Position 1 as: x' + str(position1.x) + ' y' + str(position1.y) + ' z' + str(position1.z))
if comm=="pos2":
    position2 = mc.player.getPos()
    mc.postToChat('Set Position 2 as: x' + str(position2.x) + ' y' + str(position2.y) + ' z' + str(position2.z))
if comm=="fill":
    mc.setBlocks(position1.x, position1.y, position1.z, position2.x, position2.y, position2.z, blockId, blockType)
    mc.postToChat('Filled specified area with: ' + str(blockId))
if comm=="clear":
    mc.setBlocks(position1.x, position1.y, position1.z, position2.x, position2.y, position2.z, 0)
    mc.postToChat('Cleared specified area')

每次用户通过变量'comm'输入输入时,程序都会显示以下错误消息:

Everytime the input is entered by the user through the variable 'comm' the program spits out this error message:

Traceback (most recent call last):
    File "WorldEditPi.py", line 15, in <module>
        comm=str(input('Command: '))
    File "<string>", line 1, in <module>
NameError: name 'newBlock(or what ever the user entered into 'comm')' is not defined

真正令人困惑的是,它甚至没有在谈论变量'newBlock'不是变量,而是变量'comm'的内容.所有命令都会发生这种情况,而不仅仅是'newBlock'.

Whats really confusing is that it's not even talking about a variable 'newBlock' is not a variable, it is the contents of the variable 'comm'. This occurs with all commands, not just 'newBlock'.

推荐答案

您正在使用input,因此需要使用raw_input. input计算它传递的字符串. raw_input给您一个字符串,这就是您想要的.

You're using input where you need to be using raw_input. input evaluates the string that it's passed. raw_input gives you a string, which is what you want.

请注意,这仅适用于Python2.在Python 3中,raw_input不再可用,并且input等同于Python 2的raw_input.在Python 2中,input等效于eval(raw_input)

Note that this only applies in Python 2. In Python 3, raw_input is no longer available and input is the equivalent of Python 2's raw_input. In Python 2, input is equivalent to eval(raw_input)

这篇关于变量内容中的Python NameError的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆