出现错误“ TypeError:'NoneType'对象不可迭代”

时间:2019-03-08 15:44:12

标签: python-3.x python-3.7

如何解决此错误?用户测试功能需要保留字符串和字符的输入,然后需要在反向和字符计数功能中调用这些输入。

def user_test():
    '''
    :return: hold user input
    '''
    global user_string
    global user_character
    user_string = print(input("What is the string you would like to use:"))
    user_character = print(input("What is the character you would like to use:"))
    character_count(user_string, user_character)
    reverse(user_string)
    return user_string, user_character;

def reverse(user_string):
    '''
    :param: string
    :return: reverses a string
    '''
    string = user_string
    print (list(reversed(string)))
    return string

def character_count(user_string, user_character):
    '''
    :return: counts the number of occurances of a character in a string
    '''
    string = user_string
    toCount = user_character
    counter = 0

    for letter in string:
            if( letter == toCount):
                    counter += 1
    print(counter)

def main():
    user_test()


main()

追踪

Traceback (most recent call last):
  File "C:\Users\Cheryl\Documents\Python Stuff\lab6_design.py", line 111, in <module>
    main()
  File "C:\Users\Cheryl\Documents\Python Stuff\lab6_design.py", line 108, in main
    user_test()
  File "C:\Users\Cheryl\Documents\Python Stuff\lab6_design.py", line 9, in user_test
    character_count(user_string, user_character)

  File "C:\Users\Cheryl\Documents\Python Stuff\lab6_design.py", line 34, in character_count
for letter in string:
TypeError: 'NoneType' object is not iterable

1 个答案:

答案 0 :(得分:1)

print()返回None,因此user_string和user_character为None。

user_string = print(input("What is the string you would like to use:"))
user_character = print(input("What is the character you would like to use:"))

如果仍然要打印输入内容,请将其更改为以下内容

user_string = input("What is the string you would like to use:")
print(user_string)
user_character = input("What is the character you would like to use:")
print(user_character)