Advertisement
If you have a new account but are having problems posting or verifying your account, please email us on hello@boards.ie for help. Thanks :)
Hello all! Please ensure that you are posting a new thread or question in the appropriate forum. The Feedback forum is overwhelmed with questions that are having to be moved elsewhere. If you need help to verify your account contact hello@boards.ie

ELI5: Basic Python Question

Options
  • 01-11-2019 6:39pm
    #1
    Registered Users 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 Posts: 6,010 ✭✭✭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