#1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jun 2013
    Posts
    23
    Rep Power
    0

    Variable vs Return Statement


    Hi there,

    I'm sure this's been asked many times but unfortunately, after reading some forums I still don't understand this very well, so I hope you can help here.

    I'm having a hard time understand the difference between a variable and a function with the return statement, for example:

    Code:
    number = int(input("give me a number: "))
    number2 = int(input("give me another number :"))
    def cal():
        return number+number2
    choice = input("you numbers have been added, want to see the value? y/n: ")
    if choice == "y":
        print(cal())
    else:
        print("ok, cool")
    Here, the cal() function performs a calculation, and the value is returned to the caller, then I simply call the function and it gives me its return value.

    But this code, provides the 'same' functionality

    Code:
    number = int(input("give me a number: "))
    number2 = int(input("give me another number :"))
    result = number+number2
    choice = input("you numbers have been added, want to see the value? y/n: ")
    if choice == "y":
        print((result))
    else:
        print("ok, cool")
    The 'return' variable also stores the calculation of the 2 numbers, and I can call it anytime I want.

    If someone can explain the difference hopefully using this (or a not so complicated) example I'd appreciate it very much.

    Cheers
  2. #2
  3. No Profile Picture
    Lost in code
    Devshed Supreme Being (6500+ posts)

    Join Date
    Dec 2004
    Posts
    8,317
    Rep Power
    7170
    The example you give is really too simple to highlight the power of a function, but generally speaking functions are used when you need to execute the same or similar code in more than one place in your program. They exist so that you do not need to repeat blocks of code.

    When you call a function, its body is executed each time. When you reference a variable, the value is retrieved from memory. If you do a computation to assign a value to a variable, that computation is only performed once (when you assign it), not each time you reference the variable. In your case, this means that every time you call cal(), the computer redoes the calculation number+number2; while with the result variable, number+number2 is only computed once - when the variable result is assigned.

    In this specific case, that also means that if you change number or number2, the return value of cal() would change next time you call it, but the value of the result variable would not. However, it is generally not good practice to use global variables inside functions.

    'return' is not a variable, it's a statement. The return statement does not store the calculation (looking at it from a high level), it only returns it. The code to which the value is returned may or may not choose to store the returned value in a variable. If the code to which the value is returned does not store the value, then the value is discarded from memory.

    The reasons this example is too simple too highlight the purpose of functions:
    - number1+number2 is (usually) too simple of a computation to bother putting it into a function
    - you only do the computation once in your code
    - your function doesn't have any parameters
    PHP FAQ

    Originally Posted by Spad
    Ah USB, the only rectangular connector where you have to make 3 attempts before you get it the right way around
  4. #3
  5. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jun 2013
    Posts
    23
    Rep Power
    0

    Thumbs up Thanks


    Thank you very much.

    I agree the example is probably too simple. I have writen another program and now I do see the power of the function and now I understand what 'return' does. It simply runs the code again and returns whatever value is has, and as you said, I may or may not choose to store that value in a variable.

    Have a look:

    Code:
    import time
    import urllib.request
    
    def search():
        web = urllib.request.urlopen("http://wecloudforyou.com/")
        text = web.read().decode("utf8")
        wordfind = text.find("id=")
        wordstart = wordfind+10
        wordend = wordstart+10
        return text[wordstart:wordend]
    
    print("Welcome to We Cloud for You Python lessons")
    website = input("Please past the exact URL of the website you want us to have a look at:")
    print("After the id= attribute on the website's code, normally you will find the word Technology")
    time.sleep(4)
    print("I can let you know what word follows the id= attribute now, or I can let u know if it changes to something else")
    time.sleep(4)
    print("do you want to see what it says now? or should I let you know if/when it changes?")
    time.sleep(4)
    print("Choose: ")
    time.sleep(2)
    print("now")
    time.sleep(2)
    print("changes")
    choice2 = "yes"
    while choice2 == "yes":
        choice = input("What is it going to be: ").lower()
        if choice == "now":
            print("The word is "+ search())
            choice2 = input("wanna re run the program? yes or no?")
        elif choice == "changes":
            word = "Technology"
            while word == "Technology":
                time.sleep(15)
                print("checking...")
                word = search()
            print("The word has changed! Now it says "+ search())
            choice2 = input("wanna re run the program? yes or no?")
        else:
            choice2 = input("That's not an option, wanna try again? yes or no: ")
    print("ok, cool")
    Here, the search() function searches whatever is after "id=" on the website http://wecloudforyou.com/ and returns that value.

    Thanks a lot!
  6. #4
  7. Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    May 2012
    Location
    39N 104.28W
    Posts
    158
    Rep Power
    3
    Let me add an additional point of view. A function in python is just like a function in math: y=f(x). Consider, say, the sine function. There are a few ways you might implement such a function numerically, none of them exact. In any case, you feed the function an "x" (pass it in as an argument) and it "returns" a "y" (assigns the returned value to a variable). So, like E-Oreo implied, and like you would use in, say, a graph, you might pass in successive values of "x" and map the returned "y".
  8. #5
  9. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jun 2013
    Posts
    23
    Rep Power
    0
    Thanks. It makes a lot more sense now.

IMN logo majestic logo threadwatch logo seochat tools logo