TypeError:无法隐式地将'NoneType'对象转换为str

时间:2016-05-09 20:11:47

标签: python

我是Python的新手,所以我不明白为什么我会收到以下错误:TypeError:无法隐式地将'NoneType'对象转换为str

import math, os
try:
    while True:
        loadfile = input ("Get a string from input or file: ").lower()
        if loadfile == "":
            print("You need to enter whether you want the string from input or a file. Please try again")
        elif loadfile[0] != "i" and loadfile[0] != "s" and loadfile[0] != "f":
            print("You can only choose to get the string from input or a file. Please try again")
        else:
            loadfile = loadfile[0] == "f"
            raise Execption
except Exception:
    pass

if loadfile:
    while True:
        filename = input ("Enter a file name containing a string: ")
        if filename == "":
            print("You need to enter a file name, you can not leave it blank. Please try again")
        elif not os.path.isfile(filename):
            print ("This file does not exist. Please try again")
        else:
            try:
                file = open(filename, "r")
            except OSError:
                print("Your operating system threw an error")
                print("The file may be in use, or your filename may be invalid")
            else:
                string = file.read()
                file.close()
                if os.path.getsize(filename) == 0:
                        print("Found the file vut the file is empty. Enter another file")
                else:
                    flag = False
                    for x in string:
                        if x.isalpha():
                            flag = True
                    if flag:
                        break
                    else:
                        print("The string inside this file does not contain a character from the alphabet. Please try again")
    if (len(string) <= 200):
        print ("Found the string: " + string)
    else:
        print("String found, but not being printed since it it greater than 200 characters")
else:
    try:
        while True:
            string = input ("Enter your string: ");
            if string == "":
                print ("Invalid response. You need to enter a plaintext message to be able to continue")
            else:
                for x in string:
                    if x.isalpha():
                        raise Exception;
                print ("You did not enter a character from the alphabet in your plaintext message. Please try again");
    except Exception:
        pass

string2 = ""
string3 = ""

try:
    while True:
        keyword = input ("Enter your KEYWORD: ");
        if keyword == "":
            print ("You need to enter a keyword. Please try again");
        elif keyword.isalpha():
            raise Exception;
        else:
            print ("Your keyword cannot contain any numbers, spaces, or symbols. Please try again");
except Exception:
    pass

keywordRepeated = (keyword * math.ceil(len(string)/len(keyword))).upper()

try:
    while True:
        keyword2 = input ("Enter your second KEYWORD: ");
        if keyword2 == "":
            print ("You need to enter a keyword. Please try again");
        elif keyword2.isalpha():
            raise Exception;
        else:
            print ("Your keyword cannot contain any numbers, spaces, or symbols. Please try again");
except Exception:
    pass

keyword2Repeated = (keyword2 * math.ceil(len(string)/len(keyword2))).upper()        

try:
    while True:
        decryption = input("Would you like to encrypt or decrypt?: ").lower()
        if decryption == "":
            print("You need to enter whether you want to undergo the encryption or decryption process. Please try again")
        elif decryption[0] != "d" and decryption[0] != "e":
            print("You can only choose encryption or decryption. Please try again")
        else:
            decryption = decryption[0] == "d"
            raise Exception
except Exception:
    pass

try:
    while True:
        savefile = input("Should the string be saved ot the file, or displayed on screen?: ").lower()
        if savefile == "":
            print("You need to enter whether to save the string to a file or display it on screen")
        elif savefile[0] != "d" and savefile[0] != "s" and savefile[0] != "f":
            print("You can only choose to save the string to a file or display it on screen")
        else:
            savefile = savefile[0] != "d"
            raise Exception
except Exception:
    pass

firstuppercase = ord("A"); firstlowercase = ord("a"); lastuppercase = ord("Z"); lastlowercase = ord("z");

def encryptedChar(position, parString, parKeyword):
    if not parString[position].isalpha():
        return parString[position]
    charnum = ord(parString[position])
    modifier = ord(parKeyword[position].upper()) + 1 - firstuppercase
    modifier *= -1 if decryption else 1
    charnum2 = charnum + modifier

    if decryption:
        if charnum <= lastuppercase and charnum2 < firstuppercase:
            charnum += 26
        elif charnum >= firstlowercase and charnum2 < fisrtlowercase:
            charnum += 26
    else:
        if charnum <= lastuppercase and charnum2 > lastuppercase:
            charnum2 -= 26
        elif charnum >= firstlowercase and charnum2 > lastlowercase:
            charnum2 -= 26
for x in range(len(string)):
    string2 += encryptedChar(x, string, keywordRepeated)
    string3 += encryptedChar(x, string2, keyword2Repeated)

if savefile:
    while True:
        try:
            while True:
                filename = input ("Enter a filename to save to: ")
                if filename == "":
                    print("You need to enter a file name, you cannot leave it blank")
                else:
                    raise Exception
        except Exception:
            pass

        try:
            file = open(filename, "w")
            raise Exception
        except OSError:
            print("Your operating system threw an error")
            print("The file may be in use, or your file may be invalid")
        except Exception:
            file.write(string3)
            file.close()
            print("Save successful!")
            break
else:
    print(string3)

我希望代码能够在下面运行,但我一直在使用这种类型的错误

Get a string from input or file: i
Enter your string: letters
Enter your KEYWORD: working
Enter your second KEYWORD: code
Would you like to encrypt or decrypt?: e
Should the string be saved ot the file, or displayed on screen?: d
Traceback (most recent call last):
  File "C:\Users\User\Documents\task 3.py", line 138, in <module>
    string2 += encryptedChar(x, string, keywordRepeated)
TypeError: Can't convert 'NoneType' object to str implicitly
>>> 

2 个答案:

答案 0 :(得分:1)

在Python中有三种类型的错误; RuntimeSyntax和您的TypeError

编程时,您必须了解不同的数据类型。这些可能包括:整数,浮点数,字符串,布尔值或NoneTypeNoneTypeNone对象的数据类型,它是指示无值的对象。

由于NoneType包含无值,因此无法将任何内容翻译成字符串。计算机也不知道您从哪个数据类型进行翻译,因为尚未确定。

特别参考您的问题,发生错误的行:

string2 += encryptedChar(x, string, keywordRepeated)

经过你的代码一段时间后(which may I say needs some structural work)我已经意识到这个错误非常简单。上面的行是程序中第一行使用自己编写的子程序运行的,所以这就是为什么在这里检测到错误。

简而言之,子程序:

def encryptedChar(position, parString, parKeyword):

不返回任何内容,并且您尝试将子例程的结果/值分配给变量。但是,没有结果/没有值要分配,因此NoneType.

使用子程序时,有两种类型:功能和程序。函数返回一个值,一个过程没有。在这个代码示例中,您编写了一个过程但是像函数一样使用子例程并尝试将其分配给变量。因此,在子例程结束时,您需要返回一个值来执行检测到错误的计算。您可以使用以下方法执行此操作:

return charnum2

如果想要返回一个函数,charnum2就是一个例子。或者:

return charnum, charnum2, modifier

如果想一次回馈多个值。

答案 1 :(得分:0)

问题是您尝试将NoneType用作string
我想问题是这个函数没有返回任何东西(在一种情况下),所以它实际上返回NoneType
为了从函数中添加结果,它必须返回一些东西......