gpt4 book ai didi

python - NameError : name 'form' is not defined (Python3)

转载 作者:行者123 更新时间:2023-12-03 09:06:20 24 4
gpt4 key购买 nike

基本上,main方法接受用户输入,对其进行检查,如果用户未输入first,则调用quit方法。
first方法检查输入的第一部分,并根据用户输入的内容调用其他方法之一。这就是我得到错误的地方;例如,当first方法调用form方法时,出现了NameError: name 'form' is not defined异常。我对此感到有些困惑,因为我已经定义了每个方法,而且它们的拼写都正确,而且当我调用quit方法时,它也可以很好地工作。

主要方法:

if __name__ == '__main__':
for line in sys.stdin:
s = line.strip()
if not s: break
if (str(s) == "quit"): quit()
elif (str(s) == "quit") == False:
a = s.split()
print(a)
if (len(a) is 2): first(a)
elif (len(a) is 3): first(a)
else: print("Invalid Input. Please Re-enter.")

第一种方法:
def first(a = list()):
word = a[0]

if word == "ls":
ls(a[1])
elif word == "format":
form(a[1])
elif word == "reconnect":
reconnect(a[1])
elif word == "mkfile":
mkfile(a[1])
elif word == "mkdir":
mkdir(a[1])
elif word == "append":
append(a[1], a[2])
elif word == "delfile":
delfile(a[1])
elif word == "deldir":
deldir(a[1])
else:
print("Invalid Prompt. Please Re-enter.")

其他方法(这些都是从第一个方法调用的):
def reconnect(one = ""):
print("Reconnect")

def ls(one = ""):
print("list")

def mkfile(one = ""):
print("make file")

def mkdir(one = ""):
print("make drive")

def append(one = "", two = ""):
print("append")

def form(one = ""):
print("format " + one)

def delfile(one = ""):
print("delete file")

def deldir(one = ""):
print("delete directory")

def quit():
print("quit")
sys.exit(0)

最佳答案

该错误是由于

    elif word == "format":
form(a[1])

python基本上不知道什么形式。

让我给你演示:
gaf@$[09:21:56]~> python
Python 2.7.6 (default, Jun 22 2015, 17:58:13)
[GCC 4.8.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> form()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'form' is not defined
>>>

有两种方法
>>> def form():
... pass
...
>>> form()
>>> form
<function form at 0x7f49d7f38a28>
>>>

或使用以下方法将其导入一些库
import 

命令

订单也很重要
try:
form()
except NameError:
print('Oops name error raise above')


def form():
print('form foo is called')

try:
form()
except NameError:
print('Oops name error raise below')

会给你
/home/gaf/dashboard/bin/python /home/gaf/PycharmProjects/dashboard/test.py
Oops name error raise above
form foo is called

Process finished with exit code 0

附言
看看pep8
您的代码很乱%)
但不用担心每个人对母语的处理

关于python - NameError : name 'form' is not defined (Python3),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39443624/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com