我不知道为什么我的变量没有定义。
我的代码:
def menu():
print("Please select the following option:\n 1. 1b\n 2. 2b\n 3. 3b\n 4. 4b\n 5. 5b\n")
option = input()
if option == "1":
endCol = 133
if option == "2":
endCol = 135
if option == "3":
endCol = 263
if option == "4":
endCol = 519
if option == "5":
endCol = 1031
def filebrowser(ext=""):
"Returns files with an extension"
return [f for f in glob.glob(f"*{ext}")]
menu()
x = filebrowser(".csv")
csv = input()
df2 = pd.read_csv(csv, skiprows = range(62,125), usecols = range(3,endCol))输出:
请选择下列选项:
3(投入)
'abc.csv','def.csv','ghi.csv‘
def.csv (输入)
NameError:未定义名称“endCol”
发布于 2020-04-08 07:27:18
变量endCol仅从函数menu中可见,您应该从函数中返回endCol:
def menu():
print("Please select the following option:\n 1. 1b\n 2. 2b\n 3. 3b\n 4. 4b\n 5. 5b\n")
option = input()
endCol = None
if option == "1":
endCol = 133
if option == "2":
endCol = 135
if option == "3":
endCol = 263
if option == "4":
endCol = 519
if option == "5":
endCol = 1031
return endCol
endCol = menu()发布于 2020-04-08 07:23:42
endCol是menu函数中的一个局部变量,因此不能从外部使用。您可以返回所需的值并保存以供以后使用:
def menu():
print("Please select the following option:\n 1. 1b\n 2. 2b\n 3. 3b\n 4. 4b\n 5. 5b\n")
option = input()
if option == "1":
return 133
if option == "2":
return 135
if option == "3":
return 263
if option == "4":
return 519
if option == "5":
return 1031
def filebrowser(ext=""):
"Returns files with an extension"
return [f for f in glob.glob(f"*{ext}")]
endCol = menu()
x = filebrowser(".csv")
csv = input()
df2 = pd.read_csv(csv, skiprows = range(62,125), usecols = range(3,endCol))发布于 2020-04-08 07:27:35
您必须(对于exmaple)在return endCol函数的最后一个if语句之后添加一个menu(),并在最后捕获返回值:
def menu():
print("Please select the following option:\n 1. 1b\n 2. 2b\n 3. 3b\n 4. 4b\n 5. 5b\n")
option = input()
if option == "1":
endCol = 133
if option == "2":
endCol = 135
if option == "3":
endCol = 263
if option == "4":
endCol = 519
if option == "5":
endCol = 1031
return endCol
## when calling the menu() function:
V = menu()
### you can now work with the value V:
df2 = pd.read_csv(csv, skiprows=range(62,125), usecols=range(3, V))https://stackoverflow.com/questions/61095266
复制相似问题