Search code examples
pythonpython-idle

Function in Python not producing output?


Whenever I enter the following code:

def in_fridge():
    try:
        count = fridge[wanted_food]
    except KeyError:
        count = 0
    return count

fridge = {"apples": 10, "oranges": 3, "milk": 9}
wanted_food = "apples"
in_fridge()

Into the IDLE, "10" is outputted.

When I enter the same code into the code editor and then press F5, nothing is outputted. As a test, I created a new file in the code editor, entered:

print ("Hello World") 

and dutifully got the outputted result, i.e. hello world displayed in a new window from the IDLE shell.

So I am curious as to why I get a value displayed in the IDLE environment but not the code editor, when I have entered precisely the same code.


Solution

  • You have to print that, because in IDLE the return is shown on console if not stored in a variable. Which doesn't happen when running a script, in script if something is returned by a function you need to capture that. Using = operator like result_of_func = function_name() and then print the value storred in that variable print(result_of_func)

    This will work :

    def in_fridge():
        try:
            count =fridge [wanted_food]
        except KeyError:
            count =0
        return count
    
    fridge ={"apples":10, "oranges":3, "milk":9}
    wanted_food="apples"
    print (in_fridge())
    

    Or :

    in_fridge_count = in_fridge()
    print ('Count in fridge is : ',in_fridge_count)