Estaba probando un simple código, obtén el nombre y la edad de alguien y le avisé cuando cumpliera 21 años … sin considerar los aspectos negativos y todo eso, solo al azar.
Sigo recibiendo este 'int' object is not subscriptable
error de 'int' object is not subscriptable
.
name1 = raw_input("What's your name? ") age1 = raw_input ("how old are you? ") x = 0 int([x[age1]]) twentyone = 21 - x print "Hi, " + name1+ " you will be 21 in: " + twentyone + " years."
El problema está en la línea,
int([x[age1]])
Lo que quieres es
x = int(age1)
También necesitas convertir el int en una cadena para la salida …
print "Hi, " + name1+ " you will be 21 in: " + str(twentyone) + " years."
El guión completo se ve como
name1 = raw_input("What's your name? ") age1 = raw_input ("how old are you? ") x = 0 x = int(age1) twentyone = 21 - x print "Hi, " + name1+ " you will be 21 in: " + str(twentyone) + " years."
Cuando escribe x = 0
está creando una nueva variable int
(nombre) y asignándole un cero.
Cuando x[age1]
que intenta acceder a la entrada age1
‘th, como si x
fuera una matriz.
Cuando escribes x = 0
, x
es un int … así que no puedes hacer x[age1]
porque x
es int
¿Qué estás tratando de hacer aquí: int([x[age1]])
? No tiene sentido.
Solo tienes que lanzar la entrada de edad como un int
:
name1 = raw_input("What's your name? ") age1 = raw_input ("how old are you? ") twentyone = 21 - int(age1) print "Hi, %s you will be 21 in: %d years." % (name1, twentyone)
Necesitas convertir age1 en int primero, para que pueda hacer el menos. Después de eso, devuelve el resultado a la cadena para mostrar:
name1 = raw_input("What's your name? ") age1 = raw_input ("how old are you? ") twentyone = str(21 - int(age1)) print "Hi, " + name1+ " you will be 21 in: " + twentyone + " years."
name1 = input("What's your name? ") age1 = int(input ("how old are you? ")) twentyone = str(21 - int(age1)) if age1<21: print ("Hi, " + name1+ " you will be 21 in: " + twentyone + " years.") else: print("You are over the age of 21")
Bueno, todas estas respuestas son correctas, ¡pero aquí hay una forma más moderna de hacer esto!
name1 : str = input("What's your name? ") age1 : int = int(input ("how old are you? ")) twentyone : int = 21 - age1 print('Hi, {}, you will be 21 in: {} years'.format(name1, age1))