¿Cómo puedo leer entradas como enteros?


¿Por qué este código no introduce enteros? Todo en la web dice usar raw_input(), pero leí en Stack Overflow (en un hilo que no trataba con la entrada de enteros) que raw_input() fue renombrado a input() en Python 3.x.

play = True

while play:

    x = input("Enter a number: ")
    y = input("Enter a number: ")

    print(x + y)
    print(x - y)
    print(x * y)
    print(x / y)
    print(x % y)

    if input("Play again? ") == "no":
        play = False
Author: martineau, 2013-12-08

14 answers

Python 2.x

Había dos funciones para obtener la entrada del usuario, llamadas input y raw_input. La diferencia entre ellos es, raw_input no evaluar los datos y devuelve como es, en forma de cadena. Pero, input evaluará lo que haya ingresado y el resultado de la evaluación será devuelto. Por ejemplo,

>>> import sys
>>> sys.version
'2.7.6 (default, Mar 22 2014, 22:59:56) \n[GCC 4.8.2]'
>>> data = input("Enter a number: ")
Enter a number: 5 + 17
>>> data, type(data)
(22, <type 'int'>)

Se evalúan los datos 5 + 17 y el resultado es 22. Cuando evalúa la expresión 5 + 17, detecta que está agregando dos números y así el resultado también será del mismo tipo int. Por lo tanto, la conversión de tipo se realiza de forma gratuita y 22 se devuelve como resultado de input y se almacena en la variable data. Puedes pensar en input como el raw_input compuesto con un eval igualo.

>>> data = eval(raw_input("Enter a number: "))
Enter a number: 5 + 17
>>> data, type(data)
(22, <type 'int'>)

Nota: debes tener cuidado cuando uses input en Python 2.x. Expliqué por qué uno debe tener cuidado al usarlo, en esta respuesta .

Pero, raw_input no evalúa la entrada y devuelve como es, como una cadena.

>>> import sys
>>> sys.version
'2.7.6 (default, Mar 22 2014, 22:59:56) \n[GCC 4.8.2]'
>>> data = raw_input("Enter a number: ")
Enter a number: 5 + 17
>>> data, type(data)
('5 + 17', <type 'str'>)

Python 3.x

Python 3.x input y Python 2.x raw_input son similares y raw_input no está disponible en Python 3.x.

>>> import sys
>>> sys.version
'3.4.0 (default, Apr 11 2014, 13:05:11) \n[GCC 4.8.2]'
>>> data = input("Enter a number: ")
Enter a number: 5 + 17
>>> data, type(data)
('5 + 17', <class 'str'>)

Solución

Para responder a tu pregunta, desde Python 3.x no evalúa y convierte el tipo de datos, tienes que convertir explícitamente a int s, con int, así

x = int(input("Enter a number: "))
y = int(input("Enter a number: "))

Puede aceptar números de cualquier base y convertirlos directamente a base-10 con la función int, así

>>> data = int(input("Enter a number: "), 8)
Enter a number: 777
>>> data
511
>>> data = int(input("Enter a number: "), 16)
Enter a number: FFFF
>>> data
65535
>>> data = int(input("Enter a number: "), 2)
Enter a number: 10101010101
>>> data
1365

El segundo parámetro dice cuál es la base de los números ingresados y luego internamente lo entiende y lo convierte. Si los datos ingresados son incorrectos, lanzará un ValueError.

>>> data = int(input("Enter a number: "), 2)
Enter a number: 1234
Traceback (most recent call last):
  File "<input>", line 1, in <module>
ValueError: invalid literal for int() with base 2: '1234'

Aparte de eso, su programa se puede cambiar un poco, así{[38]]}

while True:
    ...
    ...
    if input("Play again? ") == "no":
        break

Puede deshacerse de la variable play usando break y while True.

PS : Python no espera ; en el fin de la línea:)

 223
Author: thefourtheye,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-23 12:26:38

En Python 3.x, raw_input fue renombrado a input y Python 2.x input fue eliminado.

Esto significa que, al igual que raw_input, input en Python 3.x siempre devuelve un objeto string.

Para solucionar el problema, necesita hacer explícitamente esas entradas en enteros poniéndolas en int:

x = int(input("Enter a number: "))
y = int(input("Enter a number: "))

Además, Python no necesita/usa punto y coma para terminar las líneas. Por lo tanto, tenerlos no hace nada positivo.

 29
Author: iCodez,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-12-08 03:19:30

Para varios enteros en una sola línea, map podría ser mejor.

arr = map(int, raw_input().split())

Si el número ya es conocido, (como 2 enteros), puede usar

num1, num2 = map(int, raw_input().split())
 20
Author: user1341043,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-11-11 00:40:16

input() (Python 3) y raw_input() (Python 2) siempre return cadenas. Convierta el resultado a entero explícitamente con int().

x = int(input("Enter a number: "))
y = int(input("Enter a number: "))

Sugerencia pro: no se necesitan puntos y coma en Python.

 13
Author: Martijn Pieters,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-12-08 03:09:10

Las preguntas múltiples requieren la entrada de varios enteros en una sola línea. La mejor manera es introducir toda la cadena de números una línea y luego dividirlos en enteros.

 p=raw_input()
    p=p.split()      
    for i in p:
        a.append(int(i))
 8
Author: gumboy,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-07-08 00:33:57

Convertir a enteros:

my_number = int(input("enter the number"))

Del mismo modo para los números de coma flotante:

my_decimalnumber = float(input("enter the number"))
 5
Author: Hemanth Savasere,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-01-26 04:28:51

Tomando int como entrada en python: tomamos una entrada de cadena simple usando:

input()

Ahora queremos int como input.so encasillamos esta cadena a int. simplemente usando:

int(input())
 5
Author: Rohit-Pandey,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-04-16 17:35:19

Python 3.x tiene la función input() que devuelve siempre string.So usted debe convertir a int

Python 3.x

x = int(input("Enter a number: "))
y = int(input("Enter a number: "))

Python 2.x

En python 2.las funciones x raw_input() y input() siempre devuelven string, por lo que también debe convertirlas a int.

x = int(raw_input("Enter a number: "))
y = int(input("Enter a number: "))
 4
Author: Harun ERGUL,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-03-23 20:57:34

En Python 3.x. Por defecto la función de entrada toma la entrada en formato de cadena . Para convertirlo en entero es necesario incluir int (input ())

x=int(input("Enter the number"))
 4
Author: Madhusudan chowdary,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-07-13 12:55:21

Me encontré con un problema de tomar la entrada de enteros mientras resolvía un problema en CodeChef, donde dos enteros - separados por espacio - deben leerse desde una línea.

Mientras que int(input()) es suficiente para un solo entero, no encontré una manera directa de introducir dos enteros. Probé esto:

num = input()
num1 = 0
num2 = 0

for i in range(len(num)):
    if num[i] == ' ':
        break

num1 = int(num[:i])
num2 = int(num[i+1:])

Ahora uso num1 y num2 como enteros. Espero que esto ayude.

 2
Author: Aravind,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-05-23 11:32:22
def dbz():
    try:
        r = raw_input("Enter number:")
        if r.isdigit():
            i = int(raw_input("Enter divident:"))
            d = int(r)/i
            print "O/p is -:",d
        else:
            print "Not a number"
    except Exception ,e:
        print "Program halted incorrect data entered",type(e)
dbz()

Or 

num = input("Enter Number:")#"input" will accept only numbers
 2
Author: Sanyal,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-07-09 11:47:58

Mientras que en su ejemplo, int(input(...)) hace el truco en cualquier caso, python-futurebuiltins.input vale la pena considerarlo ya que asegura que su código funcione tanto para Python 2 como para 3 y deshabilita el comportamiento predeterminado de Python2 de input tratando de ser "inteligente" sobre el tipo de datos de entrada (builtins.input básicamente se comporta como raw_input).

 2
Author: Tobias Kienzler,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-11-23 12:19:52

Sí, en python 3.x, raw_input se sustituye por input. Para volver al comportamiento antiguo de input use:

eval(input("Enter a number: "))

Esto le hará saber a python que la entrada ingresada es integer

 0
Author: Waseem Akhtar,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-02-21 11:52:32
n=int(input())
for i in range(n):
    n=input()
    n=int(n)
    arr1=list(map(int,input().split()))

El bucle for se ejecutará 'n' número de veces . la segunda ' n ' es la longitud de la matriz. la última instrucción asigna los enteros a una lista y toma la entrada en forma separada por espacios . también puede devolver la matriz al final del bucle for.

 0
Author: ravi tanwar,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-08-03 16:30:31