首页 > 解决方案 > 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

标签: pythonpython-3.x

解决方案


我的理解是UNITS.get(current_units)的值不是列表或数组。该值将变为无。由于 UNITS 方法从问题中不清楚。要求您检查 UNITS 方法。


推荐阅读