TypeError: Can ' T convert 'NoneType' object to str implizit
Ich bin neu in Python, also glaube ich nicht verstehen, warum ich erhalte die folgende Fehlermeldung: TypeError: Can ' T convert 'NoneType' object to str implizit
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)
ich möchte den code ausführen, wie es unten ist, aber ich bekomme immer diese typeerror
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
>>>
- Wenn
parString[position].isalpha()
ist Wahr,encryptedChar
implizit zurückNone
. Hoffe, das hilft. - Unabhängig von der Frage selbst, aber du bist das auslösen von Ausnahmen falsch. Sie müssen, um eine Instanz der Ausnahme, nicht der Typ. Das bedeutet, dass
raise Exception()
, nichtraise Exception
Du musst angemeldet sein, um einen Kommentar abzugeben.
In Python gibt es drei Arten von Fehlern;
Runtime
,Syntax
und Ihnen einTypeError
.Bei der Programmierung müssen Sie sich bewusst sein, von verschiedenen Arten von Daten.Dazu könnten gehören: Ganzzahlen, Fließkommazahlen, Zeichenketten, Boolesche oder vielleicht ein
NoneType
. EinNoneType
ist der Datentyp, der für dieNone
- Objekt, das ein Objekt zeigt keinen Wert.Weil ein
NoneType
enthält keinen Wert, es wird nichts übersetzt werden in einen string. Der computer auch nicht weiß, von welchem Daten-Typ, den Sie übersetzen, da dies bisher noch nicht geklärt.Bezogen auf Ihr problem, in der insbesondere die Zeile, wo der Fehler aufgetreten ist:
Nachdem Sie durch Ihren code für einige Zeit (darf ich es so sagen muss einige strukturelle Arbeit) ich bin gekommen, zu erkennen, der Fehler ist ziemlich einfach. Die obige Zeile ist die erste Zeile in Ihrem Programm mit Ihren eigenen geschriebenen Unterprogramms, so ist dies, warum der Fehler erkannt wurde, hier.
Kurz gesagt, die subroutine:
nichts zurück, und Sie versuchen, zuweisen das Ergebnis/Wert an das Unterprogramm eine variable. Es ist jedoch kein Ergebnis/keine Wert zuweisen, damit die
NoneType.
Bei der Verwendung von Unterprogrammen, gibt es zwei Arten: Funktionen und Prozeduren. Funktionen einen Wert zurückgeben(s), ein Verfahren, das nicht. In diesem Beispiel ist der code, den Sie geschrieben haben ein Verfahren aber verwendet das Unterprogramm wie eine Funktion, und versucht es einer Variablen zuweisen. So, am Ende der Unterroutine, die Sie benötigen, um einen Wert zurückzugeben, um Ihre Berechnung, wo der Fehler erkannt wurde. Sie können dies tun, indem Sie Folgendes verwenden:
wenn Sie wollen, um zurückzukehren eine Funktion, wo
charnum2
ist ein Beispiel. Oder:wollte Sie zurück zu geben, mehrere Werte gleichzeitig.
Problem ist, dass Sie versuchen, eine
NoneType
alsstring
Ich denke das problem ist, dass diese Funktion nichts zurückgibt (in einem Fall), so ist es tatsächlich gibt
NoneType
Um das Ergebnis aus der Funktion, es muss etwas zurückgeben...