user3904611
user3904611

Reputation:

Python - Function calling problems

I just started learning python 2 days ago and Im trying to make some kind of text based adventure to practice , the only problem Im having is with functions:

def menu_op():
    print('1- Action 1')
    print('2- Action 2')
    choice= input('Choose action: ')
    return choice

def action_op(x):
    if x == 1:
        print('You chose action 1')
    if x == 2:
        print('You chose action 2')

menu_op()
action_op(menu_op())

The idea behind this is to call the menu function , which gives a value equal to user's input , which gets fed into the action function when the latter is called and does something depending on the user choice.

Cant tell what im doing wrong though , as the code doesnt seem to work. Thanks in advance

Upvotes: 0

Views: 95

Answers (3)

Padraic Cunningham
Padraic Cunningham

Reputation: 180391

choice= int(input('Choose action: ')) # make choice an int to compare

In [1]: 1 == "1"
Out[1]: False

In [2]: 1 == int("1")
Out[2]: True

input is a string and you are comparing if x == 1 where x is "1"

Upvotes: 0

Ashoka Lella
Ashoka Lella

Reputation: 6729

You're calling menu_op() function twice. The first time it gets called choice is not passed to action_op()

menu_op()      #return is not catched
action_op(menu_op())

And the value returned from menu_op is a string so you should compare strings in action_op instead of comparing x with integers

def action_op(x):
    if x == 1:
           ^^^  #should compare strings here ->  x == "1"

Upvotes: 1

user2555451
user2555451

Reputation:

It looks like you are using Python 3.x. In that version, input returns a string object like raw_input did in Python 2.x. This means that the return value of the function menu_op will always be a string.

Because of this, you need to compare x with strings rather than integers:

if x == '1':
    print('You chose action 1')
elif x == '2':
    print('You chose action 2')

I also changed the second if to elif since x could never equal both '1' and '2'.

Upvotes: 3

Related Questions