Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Issue with a function
#1
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')
Reply
#2
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.
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Issue in .apply function fullstop 0 1,515 Dec-17-2019, 01:29 PM
Last Post: fullstop
  return issue in a function PyPhanman 2 3,464 Apr-28-2017, 07:48 PM
Last Post: wavic

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020