Wie nehme ich eine Ganzzahleingabe in Python vor?
In diesem Beitrag erfahren Sie, wie Sie in Python ganzzahlige Eingaben vornehmen. Wie wir wissen, gibt die in Python integrierte Funktion input() immer ein Objekt der Klasse str(string) zurück. Um ganzzahlige Eingaben entgegenzunehmen, müssen wir diese Eingaben mithilfe der in Python integrierten int()-Funktion in Ganzzahlen umwandeln.
Sehen wir uns die Beispiele an:
Beispiel 1:
Python3
# take input from user> input_a> => input> ()> # print data type> print> (> type> (input_a))> # type cast into integer> input_a> => int> (input_a)> # print data type> print> (> type> (input_a))> |
Ausgabe:
100
Beispiel 2:
Python3
# string input> input_a> => input> ()> # print type> print> (> type> (input_a))> # integer input> input_b> => int> (> input> ())> # print type> print> (> type> (input_b))> |
Ausgabe:
10 20
Beispiel 3:
Python3
# take multiple inputs in array> input_str_array> => input> ().split()> print> (> 'array:'> , input_str_array)> # take multiple inputs in array> input_int_array> => [> int> (x)> for> x> in> input> ().split()]> print> (> 'array:'> , input_int_array)> |
Ausgabe:
10 20 30 40 50 60 70 array: ['10', '20', '30', '40', '50', '60', '70'] 10 20 30 40 50 60 70 array: [10, 20, 30, 40, 50, 60, 70]
Beispiel 4:
Python3
# Python program to take integer input in Python> # input size of the list> n> => int> (> input> (> 'Enter the size of list : '> ))> # store integers in a list using map, split and strip functions> lst> => list> (> map> (> int> ,> input> (> > 'Enter the integer elements of list(Space-Separated): '> ).strip().split()))[:n]> print> (> 'The list is:'> , lst)> # printing the list> |
Ausgabe:
Enter the size of list : 4 Enter the integer elements of list(Space-Separated): 6 3 9 10 The list is: [6, 3, 9, 10]