I'm doing a pokedex and I have an error when running the food function, print it in binaries

-1
import os
import sys
import marshal
import requests
import datetime
from datetime import date
from string import Template
pokemones = []
url_api=" http://pokeapi.co/api/v2/pokemon/"

class pokemon():
    nombre = ""
    tipo   = ""
    latitud = ""
    longitud = ""
    comida = ""
    sangre = ""
    ano = ""
    mes = ""
    dia = ""
    edad = ""
    signo = ""
    foto = ""
try:
    a = open("datos.pokemon","br")
    tmp = marshal.load(a)
    for z in tmp:
        p = pokemon()
        p.nombre = z[0]
        p.tipo = z[1]
        p.latitud = z[2]
        p.longitud = z[3]
        p.comida = z[4]
        p.sangre = z[5]
        p.ano = z[6]
        p.mes= z[7]
        p.dia = z[8]
        p.edad = z[9]
        p.signo = z[10]
        p.foto = z[11]
        pokemones.append(p)
    a.close()
    print("Hemos encontrador ", len(pokemones),"pokemones regristrado")
except:
    print("No hay datos regristrados...")

def menu():
    os.system("cls")
    print("---------Bienvenido a la Pokedex--------")
    print("1-Agregar pokemon")
    print("2-Ver pokemon")
    print("3-Reportes")
    print("4-Exportar pokemon")
    print("5-Exportar Mapa")
    print("6-Exit")
    tmp = input("Digite una opcion: ")
    if (tmp =="1"):
        agregarPokemon()
    elif (tmp =="2"):
        verPokemon()
    elif (tmp =="3"):
        reportes()
    elif (tmp == "4"):
        exportarPokemon()
    elif (tmp == "5"):
        exportarMapa()
    elif(tmp =="6"):
        datos = []
        for p in pokemones :
            t=[]

            t.append(p.nombre)
            t.append(p.tipo)
            t.append(p.latitud)
            t.append(p.longitud)
            t.append(p.comida)
            t.append(p.sangre)
            t.append(p.ano)
            t.append(p.mes)
            t.append(p.dia)
            t.append(p.edad)
            t.append(p.signo)
            t.append(p.foto)
            datos.append(t)
        a = open("datos.pokemon","bw")
        marshal.dump(datos,a)
        a.close()
        print("Hasta la proxima")
        sys.exit()
    else:
        print("Digite una opcion valida")
        menu()
def agregarPokemon():
    print("Vamos a agregar Pokemon")
    p = pokemon()
    nombre = input("Digite el nombre del pokemon:")
    print("Estamos validando...")  
    url = url_api + nombre.lower()
    response = requests.get(url)
    if response.status_code == 200:
        print("El pokemon que tenemos es:",nombre)
        pass
    data = response.json()
    (data["types"])

    types_pokemon = ",".join([t["type"]["name"]for t in data["types"]])
    print("Su tipo es:")
    types_pokemon = []
    for t in data["types"]:
        types_pokemon.append(t["type"]["name"])
    for s in types_pokemon:
        print(s)
    if response.status_code == 404:
        print("no lo encuentra")
        print("digite un nombre valido")

    p.nombre = nombre
    print("Esta es la fecha de hoy")
    p.tipo = s
    hoy = datetime.date.today()
    print(hoy.strftime('%d/%m/%Y'))
    print("Ahora pon la fecha de nacimiento de pokemon")
    p.ano = int(input("Digite su ano de nacimiento \n"))
    p.mes = int (input("Digite su mes de nacimiento \n"))
    p.dia = int(input("Digite su dia de nacimiento \n"))
    d= date.today()
    Calculando= (d.year)-(p.ano)
    Calculando2= (Calculando)-1
    if p.mes>d.month:
        print("su edad es:  "+str(Calculando2))
    elif p.dia>d.day:
        print("su edad es:  "+str(Calculando2))
    elif p.mes<=d.month:
        print("su edad es:  "+str(Calculando))
    elif p.dia<=d.day:
        print("su edad es:  "+str(Calculando))
    p.edad = input("Digite la edad que te muestra la pantalla \n")
    print("Muy bien")
    p.latitud = input("Digite su latitud \n")
    p.longitud = input("Digite su longitud \n")
    p.sangre = input("Digite su tipo de sangre \n")
    p.comida = input("Digite su comida \n")    
    signo = ("capricornio", "acuario", "piscis", "aries", "tauro", "géminis", "cáncer", "leo", "virgo", "libra", "escorpio", "sagitario")
    fechas = (20, 19, 20, 20, 21, 21, 22, 22, 22, 22, 22, 21)
    dia=p.dia
    mes=p.mes

    mes=mes-1
    if dia>fechas[mes]:
        mes=mes+1
    if mes==12:
        mes=0

        print ("Tu signo zodiaco es: " + signo[mes])
    p.signo = signo[mes]
    pokemones.append(p)
    input("Pokemon agregado,presione enter para volver a opcion")
    menu()
def verPokemon():
    print("Exixten",len(pokemones),"pokemon")
    s = 1
    for p in pokemones:
        print("#--Nombre: ",p.nombre)
        print("#--Latitud: ",p.latitud)
        print("#--longitud: ",p.longitud)
        print("#--Su fecha de nacimiento es: ",p.dia,"/",p.mes,"/",p.ano)
        print("#--Su tipo de sangre es: ",p.sangre)
        print("#--Su tipo de comida: ",p.comida)
        print("#--Su edad es: ",p.edad)
        print("#--El pokemon es de tipo: ",p.tipo)
        print("#--Su signo zodiacal es: ",p.signo)
        s +=1
        print('Gracias por tu estadia aqui!')
    input("Press enter para volver al menu")
    menu()
def reportes():

    print("Veremos los pokemones de mi sistema")
    print("1-Pokemones por cumpleanos")
    print("2-Pokemones por tipo")
    print("3-Pokemones que comida")
    opcion = input("Elige una opcion: ")
    if (opcion == "1"):
        cumpleanos()
    elif (opcion == "2"):
        tipo()
    elif (opcion == "3"):
        comida()
    else:
        print("Elige una opcion valida")
        reportes()
def cumpleanos():
    print("Aqui vamos a encontrar los pokemones que cumpleanos por mes")
    ap = int(input("Digite el mes en numero: "))
    for h in pokemones:
        if ap == int(h.mes):
            print("Nombre",h.nombre)
    else:
        pass
    input("Precione enter para ir a menu principa")
    menu()
def tipo():
    if opcion=="2":
            ti="electric"
            cont=0
            for x in pokemones:
                if ti ==(x.tipo):
                    cont=cont+1
                    print("Hay:",cont,x.tipo)

    else:
        pass
        menu()
def comida():
    print("Aqui vamos a encontrar a los pokemones por comidas")
    for pokemon in pokemones:
        j = []
        j.append(p.comida)
        j.append(p.comida)
        print(pokemon)
    else:
        pass
    input("Precione enter para ir a menu principa")
    menu()

def  exportarPokemon():
    filein = open("Template/Perfil.html")
    src = Template(filein.read())
    nombre = p.nombre
    latitud = p.latitud
    longitud = p.longitud
    fecha_nac = p.dia,p.mes,p.ano
    tipo_sang = p.sangre
    tipo_com = p.comida
    tipo = p.tipo
    signo = p.signo
    edad = p.edad


    d={"nombre":nombre, "latitud":latitud, "longitud":longitud, "fecha_nac":fecha_nac,"edad":edad,
         "tipo_sang":tipo_sang,"tipo_com":tipo_com,"tipo":tipo,"signo":signo,}
    result = src.substitute(d)

    try:
        os.mkdir("Pokemones")
        filein2 = open("pokemones/"+str(nombre)+".html", "w")
        filein2.writelines(result)

        print("Creando una carpeta")
        print("Guardando archivo")

    except OSError:
        if os.path.exists("Pokemones"):
            filein2= open("Pokemones"+".html", "a")
            filein2.writelines(result)
            print("guardando archivo")

    while True:
        question = input("Press S si quieres seguir y E si quieres salir")
        if question == "S":
            os.system("Combazoo.py")
        elif question == "E":
            sys.exit()
menu()
    
asked by Manuel Ramirrez 29.07.2018 в 22:27
source

2 answers

0

If when you ask the actor to enter the type of food instead of input you use raw_input it should work. If not, the other option is to print the variable to string with str (p.comida) .

I hope it helps greetings.

    
answered by 30.07.2018 в 22:23
0

I assume you mean the function

def comida():
    print("Aqui vamos a encontrar a los pokemones por comidas")
    for pokemon in pokemones:
        j = []
        j.append(p.comida)
        j.append(p.comida)
        print(pokemon)
    else:
        pass
    input("Precione enter para ir a menu principa")
    menu()

In the line print(pokemon) to be an instance of a class without method __str__ or __repr__ shows you only its class name and its memory address (location within the RAM of the computer where you run your program)

You can modify your Pokemon class by adding the missing method:

class Pokemon():
    def __init__(self):
        self.nombre = ''
        self.tipo   = ''
        self.latitud = ''
        self.longitud = ''
        self.comida = ''
        self.sangre = ''
        self.ano = ''
        self.mes = ''
        self.dia = ''
        self.edad = ''
        self.signo = ''
        self.foto = ''

    def __str__(self):
        try:
            return f"<Pokemon> {self.nombre} ({self.tipo})"
        except SyntaxError:
            return "<Pokemon> {} ({})".format(self.nombre, self.tipo)

Several clarifications:

  • According to the Python style rules, the class names must be in CamelCase (all words together with the first letter of each word in capital letters, for example: Pokemon , ClinicaPokemon TipoPokemon , etc)
  • As mentioned by @FJSevilla you should change your class attributes to instance attributes. I share your link: Difference between class attributes and instance attributes
  • I do not know if you're using python 3.6 so I put two options in the __str__ method. The first one makes use of the fstring (in English), and in case of that you are using a version of python < 3.6.0 will use the format() method by means of except SyntaxError . Depending on which version you should choose one or the other.
answered by 31.07.2018 в 21:28