简体   繁体   中英

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, ie 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 enviroment but not the code editor, when I have entered precisely the same code :(

You've called in_fridge but you haven't done anything with the result. You could print it, for example:

result = in_fridge()
print(result)

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)

You are not priting the result of the in_fridge call, you should print it:

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())

为了显示输出,您需要打印它:

print(in_fridge())

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM