pythonsohard
pythonsohard

Reputation: 127

Python defined functions doesn't work properly

Hi so my school is doing an RPG project on python, and i have encountered a problem where i define my own functions, and needs to call one of them inside another, and it doesn't work. The following code for example:

from characters1 import *

def printmana(typeofenemy):
    print typeofenemy.mana


def printmany(typeofenemy):
    print typeofenemy.damage
    print typeofenemy.health
    option = raw_input("Type something ")
    if option == 1:
        printmana(typeofenemy)

printmany(Goblin)

when i call printmany(Goblin), everything goes fine until i type in 1, where i expect it to call printmana(Goblin) and print Goblin.mana, but it doesn't. Yet when i call printmana(Goblin) separately, it works absolutely fine. I also tried this:

from characters1 import *

def printmana(typeofenemy):
    return (typeofenemy.mana)


def printmany(typeofenemy):
    print typeofenemy.damage
    print typeofenemy.health
    option = raw_input("Type something ")
    if option == 1:
        print (printmana(typeofenemy))

printmana(Goblin)

Where i thought i change the print in printmana as return, and call the print printmana(Goblin) in the second function, yet it still doesn't work when i type in 1. There must be some thing i don't yet understand about the nature of python functions, so can someone please explain why is my example code not working? Thank you!

Upvotes: 1

Views: 187

Answers (4)

Casey
Casey

Reputation: 71

You set the variable "option" to become whatever the user types in. If the user types '1' and hits return, "option" will hold the string value, '1'. So, the issue is in your "if" statement, where you compare a string and a integer.

Upvotes: 1

Vadim Key
Vadim Key

Reputation: 1234

Option is a string in this code:

>>> option = raw_input("Type something ")
Type something 1
>>> print option
1
>>> print type(option)
<type 'str'>
>>> print option == 1
False
>>> print option == "1"
True 

So you need change the if to:

if option == "1":

Upvotes: 3

John Percival Hackworth
John Percival Hackworth

Reputation: 11531

raw_input doesn't cast the value to an integer. You could compare option to a string, i.e:

if option == '1':

Or you could convert option to an int, i.e.:

option = int(option)

Be aware that the second choice has some interesting gotchas if the value can't be converted to an int.

Upvotes: 1

CrazyCasta
CrazyCasta

Reputation: 28302

Your trouble is that you're comparing the output of raw_input (a string) with an integer. Try one of the following:

if option == "1":
    ...

or

if int(option) == 1:
    ...

Upvotes: 3

Related Questions