Python Forum

Full Version: Issue with a function
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi,

No matter what number I select from the below code, the test() function is always fired. Why or, how to fix it?

TIA

#!/usr/bin/python3

import sys

# to test it:
# python3 testsys.py 1
# if we want to get 1 

def f(x):
    return {
      '1':17,
      '2':18,
      '3':test(),
      '4':23,
      }[x]

def test():
  print('testing funtion')

if __name__ == "__main__":
  try:
    a = f(sys.argv[1])
    print('You selected {}'.format(a))
  except RuntimeError:
    print('Runtime Error')
  except KeyError:
    print('Wrong number')
on line 13, remove the ()
def f(x):
    return {
      '1':17,
      '2':18,
      '3':test,
      '4':23,
      }[x]
however, note that in case x==3 it will return a function object and not execute it.
You need to elaborate further what you want to achieve.

To explain the problem in greater detail - when executing the f function it has to create the dict before being able to get value for key x from it. Because of the parenthesis it actually execute the test function, while creating the dict. If x==3 you will notice that it returns None.
On second thought, if you want to get the result of the test function

import sys
 
# to test it:
# python3 testsys.py 1
# if we want to get 1 
 
def f(x):
    return {
      '1':17,
      '2':18,
      '3':test(),
      '4':23,
      }[x]
 
def test():
  return 'testing funtion'
 
if __name__ == "__main__":
  try:
    a = f(sys.argv[1])
    print('You selected {}'.format(a))
  except RuntimeError:
    print('Runtime Error')
  except KeyError:
    print('Wrong number')
Note that it will always execute the test function, assign the return value to key 3 and only if x==3 it will get that value.