logo

Com prendre l'entrada de nombres enters a Python?

En aquesta publicació, veurem com prendre l'entrada de nombres enters a Python. Com sabem que la funció d'entrada () integrada de Python sempre retorna un objecte de classe str (cadena). Per tant, per prendre l'entrada de nombres enters hem d'escriure emetre aquestes entrades en nombres enters utilitzant la funció int() integrada de Python.

Vegem els exemples:

Exemple 1:



Python 3


exportar gimp com a jpg



# 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))>

>

>

Sortida:

100>

Exemple 2:

Python 3




# string input> input_a>=> input>()> # print type> print>(>type>(input_a))> # integer input> input_b>=> int>(>input>())> # print type> print>(>type>(input_b))>

>

>

Sortida:

10 20>

Exemple 3:

Python 3




# 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)>

>

>

Sortida:

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]>

Exemple 4:

Python 3




# 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>

>

>

Sortida:

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]>