Ich mache ein Programm, das bestimmt, welcher Typ die Eingabe ist (int, float oder str), aber ich weiß, dass die Funktion input() Eingaben als Strings akzeptiert, also stecke ich ein bisschen fest.
stuff = input('Enter something: ')
print('Input is int?', stuff == int(stuff))
print('Input is float?', stuff == float(stuff))
print('Input is string?', stuff == str(stuff))
Der obige Code dient nur dazu, einen Kontext bereitzustellen, er funktioniert jedoch nicht wirklich.
Oder der praktischere Weg:
stuff = input('Enter something: ')
print(type(stuff))
Aber es kommt immer zurück <class 'str'>
, was nicht immer die richtige Antwort liefert, zB was, wenn ich "10" eingebe? Irgendwelche Ideen, wie man den Typ der Eingabe ändert?
Lösung des Problems
Mach so etwas:
stuff = input('Enter something: ')
try:
# first you try an int, which is the most restrictive one
stuff = int(stuff)
print("It's an int")
except ValueError:
# then you try a float which is less restrictive
try:
stuff = float(stuff)
print("It's a float")
except ValueError:
# if both conversions fail, it's a string
print("Looks like it's a string after all")
Keine Kommentare:
Kommentar veröffentlichen