0

When I try to return a function as an integer, and then use that integer in another function, the argument becomes a type 'function'

example:

def makeChoice():
    c = 0
    if input='yes':
        c = 1
    return int(c)

def choiceMade(c)
    if c == 1:
        print('finally this damn thing works')

while True:
    choiceMade(makeChoice)

if I debug choiceMade(c) with print(c), I get "function at x980342" instead of an integer, and the if/else statement never is true.

I was under the impression that python functions could be called as arguments so now I am not sure what I am doing wrong.

Alex W
  • 9
  • 2

2 Answers2

4

You need to call makeChoice. In Python, functions are objects, and transmitting the function (without calling it) to various parts of the program is sending the entire function object to be called later. In this case, you need to access the returned object, the integer:

while True:
   choiceMade(makeChoice())

Also, note that you need to use == instead of = in makeChoice. = is for assignment, while == is for comparison only:

new makeChoice:

def makeChoice():
   c = 0
   if input=='yes':
      return int(c)

Additionally, a : is needed at the end of the function header choiceMade:

def choiceMade(c):
   if c == 1:
     print('finally this damn thing works')
Ajax1234
  • 69,937
  • 8
  • 61
  • 102
  • Thanks. This is just a rough version of my code but you're right. I am properly using == and : in my code already though. My issue was keeping the parentheses in the called function (ie "choiceMade(makeChoice())" instead of choiceMade(makeChoice) – Alex W Jan 26 '18 at 03:20
  • @AlexW "My issue was keeping the parentheses in the called function (ie "choiceMade(makeChoice())" instead of choiceMade(makeChoice)" -- not really – englealuze Jan 26 '18 at 17:22
1

Another way is to delay the execution of your function, thus modify your choiceMade. So that you can still use the same way to call your function choiceMade(makeChoice)

def makeChoice():
    c = 0
    if input == 'yes':
        c = 1
    return int(c)

def choiceMade(c):
    if c() == 1:
        print('finally this damn thing works')

while True:
    choiceMade(makeChoice)
englealuze
  • 1,445
  • 12
  • 19