Why does returning in Interactive Python print to sys.stdout?

后端 未结 5 1494
挽巷
挽巷 2021-01-16 04:18

I ran into something different today. Consider this simple function:

def hi():
    return \'hi\'

If I call it in a Python shell,

         


        
5条回答
  •  情歌与酒
    2021-01-16 04:49

    In Python's interactive mode, expressions that evaluate to some value have their repr() (representation) printed. This so you can do:

    4 + 4
    

    Instead of having to do:

    print(4 + 4)
    

    The exception is when an expression evaluates to None. This isn't printed.

    Your function call is an expression, and it evaluates to the return value of the function, which isn't None, so it is printed.

    Interestingly, this doesn't apply to just the last value evaluated! Any statement that consists of an expression that evaluates to some (non-None) value will print that value. Even in a loop:

    for x in range(5): x
    

    Different Python command lines can handle this in different ways; this is what the standard Python shell does.

提交回复
热议问题