xiaofo
xiaofo

Reputation: 67

python function call by using tuple

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 ?

Upvotes: 0

Views: 107

Answers (2)

Genie
Genie

Reputation: 129

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.

Upvotes: 0

hiro protagonist
hiro protagonist

Reputation: 46849

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.

Upvotes: 2

Related Questions