簡體   English   中英

Python NameError來自變量的內容

[英]Python NameError from contents of a variable

我一直為Raspberry Pi版本的Minecraft制作一個mod,每次我輸入程序中的一個命令時,我都會遇到一個非常令人沮喪的錯誤。 這是我的代碼:

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'輸入輸入時,程序都會發出以下錯誤消息:

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'。

您正在使用input ,您需要使用raw_input input評估它傳遞的字符串。 raw_input為你提供了一個字符串,這就是你想要的。

請注意,這僅適用於Python 2.在Python 3中, raw_input不再可用, input等同於Python 2的raw_input 在Python 2中, input等效於eval(raw_input)

當您使用input()輸入newBlock時,解析器將newBlock視為變量而不是string。 所以你需要使用raw_input

看到輸入的ref()

def input(prompt):
    return (eval(raw_input(prompt)))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM