3

I have been working at learning Python over the last week and it has been going really well, however I have now been introduced to custom functions and I sort of hit a wall. While I understand the basics of it, such as:

def helloworld():
    print("Hello World!")

helloworld()

I know this will print "Hello World!".

However, when it comes to getting information from one function to another, I find that confusing. ie: function1 and function2 have to work together to perform a task. Also, when to use the return command.

Lastly, when I have a list or a dictionary inside of a function. I'll make something up just as an example.

def my_function():
    my_dict = {"Key1":Value1,
              "Key2":Value2,
              "Key3":Value3,
              "Key4":Value4,}

How would I access the key/value and be able to change them from outside of the function? ie: If I had a program that let you input/output player stats or a character attributes in a video game.

I understand bits and pieces of this, it just confuses me when they have different functions calling on each other.

Also, since this was my first encounter with the custom functions. Is this really ambitious to pursue and this could be the reason for all of my confusion? Since this is the most complex program I have seen yet.

7
  • Always use return inside a function. Commented Jul 30, 2013 at 1:36
  • I think you'll have to be more specific. Can you give an example of something you might want to do? Commented Jul 30, 2013 at 1:38
  • @SantoshKumar I think that's a good guideline, but not every function should use return. A good example is functions that only use print. Commented Jul 30, 2013 at 1:40
  • I'll post something as an example. =] Commented Jul 30, 2013 at 1:41
  • @SethMMorton we can always use print(my_function) for that condition. Commented Jul 30, 2013 at 1:43

3 Answers 3

4

Functions in python can be both, a regular procedure and a function with a return value. Actually, every Python's function will return a value, which might be None.

If a return statement is not present, then your function will be executed completely and leave normally following the code flow, yielding None as a return value.

def foo():
    pass
foo() == None
>>> True

If you have a return statement inside your function. The return value will be the return value of the expression following it. For example you may have return None and you'll be explicitly returning None. You can also have return without anything else and there you'll be implicitly returning None, or, you can have return 3 and you'll be returning value 3. This may grow in complexity.

def foo():
   print('hello')
   return
   print('world')

foo()
>>>'hello'

def add(a,b):
    return a + b
add(3,4)
>>>7

If you want a dictionary (or any object) you created inside a function, just return it:

def my_function():
    my_dict = {"Key1":Value1,
              "Key2":Value2,
              "Key3":Value3,
              "Key4":Value4,}
    return my_dict
d = my_function()
d['Key1']
>>> Value1

Those are the basics of function calling. There's even more. There are functions that return functions (also treated as decorators. You can even return multiple values (not really, you'll be just returning a tuple) and a lot a fun stuff :)

def two_values():
    return 3,4
a,b = two_values()
print(a)
>>>3
print(b)
>>>4

Hope this helps!

Sign up to request clarification or add additional context in comments.

4 Comments

In the def foo() example, where it is return print("world") what would the purpose of that be, also, how would you actually have the function print that instance of "world"?
It's purpose is to show you that the return statement finished the function execution. Anything under it is not executed (it's pretty clear though but still, just wanted to show)
Oh okay, thank you. So the print("world") after return would never be executed and/or inaccessible?
Right, clever text editors will warn you about inaccessible code.
3

The primary way to pass information between functions is with arguments and return values. Functions can't see each other's variables. You might think that after

def my_function():
    my_dict = {"Key1":Value1,
              "Key2":Value2,
              "Key3":Value3,
              "Key4":Value4,}
my_function()

my_dict would have a value that other functions would be able to see, but it turns out that's a really brittle way to design a language. Every time you call my_function, my_dict would lose its old value, even if you were still using it. Also, you'd have to know all the names used by every function in the system when picking the names to use when writing a new function, and the whole thing would rapidly become unmanageable. Python doesn't work that way; I can't think of any languages that do.

Instead, if a function needs to make information available to its caller, return the thing its caller needs to see:

def my_function():
    return {"Key1":"Value1",
            "Key2":"Value2",
            "Key3":"Value3",
            "Key4":"Value4",}
print(my_function()['Key1']) # Prints Value1

Note that a function ends when its execution hits a return statement (even if it's in the middle of a loop); you can't execute one return now, one return later, keep going, and return two things when you hit the end of the function. If you want to do that, keep a list of things you want to return and return the list when you're done.

Comments

2

You send information into and out of functions with arguments and return values, respectively. This function, for example:

def square(number):
    """Return the square of a number."""
    return number * number

... recieves information through the number argument, and sends information back with the return ... statement. You can use it like this:

>>> x = square(7)
>>> print(x)
49

As you can see, we passed the value 7 to the function, and it returned the value 49 (which we stored in the variable x).

Now, lets say we have another function:

def halve(number):
    """Return half of a number."""
    return number / 2.0

We can send information between two functions in a couple of different ways.

  1. Use a temporary variable:

    >>> tmp = square(6)
    >>> halve(tmp)
    18.0
    
  2. use the first function directly as an argument to the second:

    >>> halve(square(8))
    32.0
    

Which of those you use will depend partly on personal taste, and partly on how complicated the thing you're trying to do is.

Even though they have the same name, the number variables inside square() and halve() are completely separate from each other, and they're invisible outside those functions:

>>> number
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'number' is not defined

So, it's actually impossible to "see" the variable my_dict in your example function. What you would normally do is something like this:

def my_function(my_dict):
    # do something with my_dict
    return my_dict

... and define my_dict outside the function.

(It's actually a little bit more complicated than that - dict objects are mutable (which just means they can change), so often you don't actually need to return them. However, for the time being it's probably best to get used to returning everything, just to be safe).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.