0

I am writing code utilizing tuple for function call

def get_apple():
    print('you got an apple.')

def get_pear():
    print('you got a pear.')

fruits = (get_apple, get_pear)

print('0. apple\n1. pear')
s = eval(input('which one : '))

fruits[s]()

But once I execute this script, it only returns "TypeError: 'function' object is not subscriptable" on "fruitss".

Does anyone have an idea ?

5
  • return some value from get_apple and get_pear. Commented Feb 26, 2019 at 14:22
  • 2
    I don't get an error using python 3.6 Commented Feb 26, 2019 at 14:23
  • 2
    Not reproducible. Please provide a minimal reproducible example. Also you should avoid eval at all cost because it's unsafe. Just use int(input('which one : ')). For example try type exit() when prompted for input. Commented Feb 26, 2019 at 14:24
  • 1
    This code works, your error would trigger on get_apple[s], but that ain't the case Commented Feb 26, 2019 at 14:24
  • 1
    Why are you using eval? Get rid of it; you know you want s to be an int, so use int(input(...)) instead. Commented Feb 26, 2019 at 14:25

2 Answers 2

2

you could just do this:

def get_apple():
    print('you got an apple.')

def get_pear():
    print('you got a pear.')

fruits = (get_apple, get_pear)

n = int(input('0. apple\n1. pear'))

fruits[n]()

there is no need for eval.

you'd have to check for non-integer input of course.

Sign up to request clarification or add additional context in comments.

Comments

0
def get_apple():
    print('you got an apple.')

def get_pear():
    print('you got a pear.')

fruits = (get_apple, get_pear)

print('0. apple\n1. pear')
s = eval(str(input('which one : ')))

fruits[s]()

This code worked in both python 2.7.5 and python 3.7.1.

eval() takes input string as input . Hence converting input to str.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.