Domanda

Sto scrivendo un semplice programma per aiutare a generare ordini per un gioco di cui sono membro. Cade nella categoria dei programmi che in realtà non mi servono. Ma ora ho iniziato, voglio che funzioni. Funziona praticamente senza intoppi, ma non riesco a capire come fermare un errore di tipo che si verifica a metà strada. Ecco il codice;

status = 1

print "[b][u]magic[/u][/b]"

while status == 1:
    print " "
    print "would you like to:"
    print " "
    print "1) add another spell"
    print "2) end"
    print " "
    choice = input("Choose your option: ")
    print " "
    if choice == 1:
        name = raw_input("What is the spell called?")
        level = raw_input("What level of the spell are you trying to research?")
        print "What tier is the spell: "
        print " "
        print "1) low"
        print "2) mid"
        print "3) high"
        print " "
        tier = input("Choose your option: ")
        if tier == 1:
            materials = 1 + (level * 1)
            rp = 10 + (level * 5)
        elif tier == 2:
            materials = 2 + (level * 1.5)
            rp = 10 + (level * 15)
        elif tier == 3:
            materials = 5 + (level * 2)
            rp = 60 + (level * 40)
        print "research ", name, "to level ", level, "--- material cost = ",
                materials, "and research point cost =", rp
    elif choice == 2:
        status = 0

Qualcuno può aiutare?

modifica

L'errore che ottengo è;

Traceback (most recent call last):
  File "C:\Users\Mike\Documents\python\magic orders", line 27, in <module>
    materials = 1 + (level * 1)
TypeError: unsupported operand type(s) for +: 'int' and 'str'
È stato utile?

Soluzione

Uno stacktrace avrebbe aiutato, ma presumibilmente l'errore è:

materials = 1 + (level * 1)

"level" è una stringa e non puoi eseguire l'aritmetica sulle stringhe. Python è un linguaggio tipizzato in modo dinamico, ma non un linguaggio debole.

level= raw_input('blah')
try:
    level= int(level)
except ValueError:
    # user put something non-numeric in, tell them off

In altre parti del programma stai usando input (), che valuterà la stringa inserita come Python, quindi per “1” ti darà il numero 1.

Ma! Questo è super-pericoloso - immagina cosa succede se l'utente digita "os.remove (nome file)" anziché un numero. A meno che l'utente sia solo tu e non ti interessi, non utilizzare mai input (). Andrà via in Python 3.0 (il comportamento di raw_input verrà rinominato input).

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top