0

why does the following code produces a value hello when assignment statements are not supposed to produce a value and why just hello and not hello world?

def f1():
  print 'hello'
def f2():
  return 'world'
f1=f1()
f2=f2()
ggorlen
  • 44,755
  • 7
  • 76
  • 106
  • 4
    Because you are printing `hello` and assigning `world` to `f2` but you aren't doing anything with it. – Guy Jan 21 '20 at 05:41

3 Answers3

0

The functions f1() and f2() are called in the last two statements, and their return values are stored in f1 and f2, respectively. When, f1() is called, it prints 'hello' and returns None. When f2() is called, it returns 'world'. Try to learn how functions work, their calling and return values. Try printing the values of f1 and f2 to see yourself.

NixMan
  • 543
  • 4
  • 9
0

Return has to be used. You are Printing 'Hello' to screen but You are just Returning 'World'. To print it You should use:

def f2():
  return 'world'
print(f2())

Or if you don't want to Print and use the returned value for some other purpose then you should store it in a variable:

def f1():
  print 'hello'
def f2():
  return 'world'
f1
f2=f2()
print(f2)  # print the value stored in f2 i.e: 'World'
M Umair
  • 187
  • 1
  • 1
  • 13
0

There are two different concepts to handle here, assignments and function.

  • What do assignments do?

It stores the value of something at the right of the assignment inside a variable at the left of the assignment, that could then be used later.

  • What does a function do?

It permits to do anything and can return a value (or not) after that.

Your f1 function print 'hello' and then return nothing. Your f2 function do nothing and return "world". Then you have an f1 and f2 variable with the exact same name as the function (this is confusing) that contains what is returned by f1 and f2. If we remove the functions you're code does this :

print 'hello'
f1=None # Nothing in 'Python'
f2='world'
Pierre.Sassoulas
  • 3,733
  • 3
  • 33
  • 48