Advertisement
Help Keep Boards Alive. Support us by going ad free today. See here: https://subscriptions.boards.ie/.
If we do not hit our goal we will be forced to close the site.

Current status: https://keepboardsalive.com/

Annual subs are best for most impact. If you are still undecided on going Ad Free - you can also donate using the Paypal Donate option. All contribution helps. Thank you.
https://www.boards.ie/group/1878-subscribers-forum

Private Group for paid up members of Boards.ie. Join the club.

ELI5: Basic Python Question

  • 01-11-2019 06:39PM
    #1
    Registered Users, Registered Users 2 Posts: 1,799 ✭✭✭


    I'd appreciate some help in stepping through this (basic) code.
    def metal(a):
      albums = {1984:"Reign in Blood", 1990:"Seasons in the Abyss", 1985:"Hell Awaits", 2001:"God Hates Us All" }
      choice = albums.get(a)
    
      if choice:
        return choice
      return "?"
    
    print(metal(1990))
    

    My question relates to how Arguments operate within the Function.
    Would it be fair to say, Argument 'a' acts like a temporary variable? So, '1990' is passed into 'a' which then looks up the Dictionary and pulls out 'Seasons in the Abyss'?


Comments

  • Registered Users, Registered Users 2 Posts: 7,188 ✭✭✭Talisman


    The idea of temporary variables suggests that the space allocated to the variable is temporary so successive calls to the function would mean different memory space would be allocated to the variable name.

    Python uses objects and every object has a unique id which you can find using the built-in 'id()' function. If the variables are temporary then succesive calls to the function below will display different results.
    def metal(a):
        albums = {1984:"Reign in Blood", 1990:"Seasons in the Abyss", 1985:"Hell Awaits", 2001:"God Hates Us All" }
        choice = albums.get(a)
        print("id(a) =", id(a))
        print("id(albums) =", id(albums))
        print("id(choice) =", id(choice))
        if choice:
            return choice
        return "?"
    
    print(metal(1990))
    

    Your function call metal(1990) passes the value 1990 as the first positional argument to the function. The function definition only contains a single argument so the value is assigned to that variable name 'a'. 'a' is a local variable within the scope of the 'metal' function. Think of the 'metal' function as a box within which 'a' lives.


Advertisement