python - TypeError:“NoneType”对象不可下标,仅在第二次迭代时显示?
问题描述
我遇到了一个非常奇怪的错误。函数Choose_units() 在循环中被调用。它在第一次调用时有效,但第二次出现此错误。错误出现在“units_used = UNITS.get(current_units)[0]”行上,我在该行之前使用了一些检查,它显示 current_units != None。我们被要求在赋值中使用 current_units 作为全局变量。
我在该行之前使用了一些检查,它显示 current_units != None。但它仍然显示相同的错误,并且由于某种原因不在第一次迭代中。
while True:
print_menu();
try:
choice = int(input("What is your choice?: "));
except:
print("Please enter an integer only");
continue;
if choice == 1:
Process_a_new_data_file(current_set);
elif choice == 2:
Choose_units();
def Choose_units():
global current_units
if current_units is not None:
print("a")
print(current_units)
units_used = UNITS.get(current_units)[0]
print("Current units in " + units_used)
print("Choose new units:\n")
for i in UNITS:
print(str(i) + " - " + UNITS[i][0])
while True:
current_units = input("Which unit?\n")
for i in UNITS:
if(int(current_units) == i):
return
print("Please choose a unit from the list")
continue
它应该可以在不显示错误的情况下工作。
我的示例运行:
Main Menu
---------
1 - Process a new data file
2 - Choose units
3 - Edit room filter
4 - Show summary statistics
5 -Show temperature by date and time
6 -Show histogram of temperatures
7 - Quit
What is your choice?: 2
a
0
Current units in Celsius
Choose new units:
0 - Celsius
1 - Fahrenheit
2 - Kelvin
5 - Rankine
Which unit?
1
Main Menu
---------
1 - Process a new data file
2 - Choose units
3 - Edit room filter
4 - Show summary statistics
5 -Show temperature by date and time
6 -Show histogram of temperatures
7 - Quit
What is your choice?: 2
a
1
Traceback (most recent call last):
File "Assignment9.py", line 274, in <module>
main()
File "Assignment9.py", line 253, in main
Choose_units();
File "Assignment9.py", line 79, in Choose_units
units_used = UNITS.get(current_units)[0]
TypeError: 'NoneType' object is not subscriptable
解决方案
我的理解是UNITS.get(current_units)的值不是列表或数组。该值将变为无。由于 UNITS 方法从问题中不清楚。要求您检查 UNITS 方法。
推荐阅读
- python - 由于 ezsheets 和 ezgmail 模块,将 python 脚本打包到 .exe 文件时出错
- ossec - Wazuh 子解码器未正确解析字段
- ruby-on-rails - gem在wsl2上安装mysql,ubuntu 20.04失败
- shopify - 在 Shopify 集合页面上修复 3xx 重定向
- vue.js - 将vue2.x的代码迁移到vue3.x,遇到v-model模块中“task”prop的Unexpected mutation
- android - Flutter - showSlidingBottomSheet 初始快照未发生
- google-drive-api - Laravel 8 将文件上传到 Google 云端硬盘
- spartacus-storefront - 节点服务器重启问题
- r - 为什么我的条形图值在 R 中看起来变形?这
- python - VSCode 从终端启动时不使用 conda 环境