关于python:TypeError:无法将’NoneType’对象隐式转换为str

TypeError: Can't convert 'NoneType' object to str implicitly

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
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)

我希望代码按下面的方式运行,但是我不断收到此typeerror

1
2
3
4
5
6
7
8
9
10
11
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
>>>


在Python中,错误分为三种: RuntimeSyntax,而您是TypeError

编程时必须注意不同的数据类型,其中可能包括:整数,浮点数,字符串,布尔值或NoneTypeNoneTypeNone对象的数据类型,该对象是表示没有值的对象。

因为NoneType不包含任何值,所以没有任何内容可以转换为字符串。由于还没有识别出计算机,计算机也不知道从哪个数据类型进行转换。

特别是提到您的问题,发生错误的行:

1
string2 += encryptedChar(x, string, keywordRepeated)

在经过一段时间的代码(也许可以说需要做一些结构工作)之后,我开始意识到错误非常简单。上面的行是您的程序中使用您自己的书面子例程运行的第一行,因此这就是为什么在此处检测到错误的原因。

简而言之,子例程:

1
def encryptedChar(position, parString, parKeyword):

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

使用子例程时,有两种类型:函数和过程。函数返回一个值,而过程则不返回。在此代码示例中,您已编写了一个过程,但将子例程用作函数,并尝试将其分配给变量。因此,在子例程的末尾,您需要返回一个值以执行检测到错误的位置的计算。您可以使用以下方法完成此操作:

1
return charnum2

如果要返回一个函数,以charnum2为例。要么:

1
return charnum, charnum2, modifier

如果想一次返回多个值。


问题是您尝试将NoneType用作string
我想问题是此函数不返回任何值(在一种情况下),因此它实际上返回NoneType
为了添加函数的结果,它必须返回一些内容。