Is it more efficiant to repeat a text phrase or insert a variable for that phrase?

Say I take the phrase "Please insert your answer here" and wish to repeat it many times within a program would it be more efficient to print "Please insert your answer here" or to create a variable with that text to do the same function?

#First option
answer= input("Please insert your answer here ")

#second option
prepared_question= "Please insert your answer here "
answer= input(prepared_question)

Assuming this would be repeated many times, would there be a more efficient option?

1 answer

  • answered 2018-01-13 17:10 Kasramvd

    The first one is (slightly) more efficient because it doesn't require two extra steps of STORE_NAME and LOAD_NAME during the interpretation.

    In [3]: dis.dis("answer= input('Please insert your answer here')")
      1           0 LOAD_NAME                0 (input)
                  3 LOAD_CONST               0 ('Please insert your answer here')
                  6 CALL_FUNCTION            1 (1 positional, 0 keyword pair)
                  9 STORE_NAME               1 (answer)
                 12 LOAD_CONST               1 (None)
                 15 RETURN_VALUE
    
    In [5]: dis.dis("prepared_question= 'Please insert your answer here';answer= input(prepared_question)")
      1           0 LOAD_CONST               0 ('Please insert your answer here')
                  3 STORE_NAME               0 (prepared_question)
                  6 LOAD_NAME                1 (input)
                  9 LOAD_NAME                0 (prepared_question)
                 12 CALL_FUNCTION            1 (1 positional, 0 keyword pair)
                 15 STORE_NAME               2 (answer)
                 18 LOAD_CONST               1 (None)
                 21 RETURN_VALUE
    

    But from the functionality perspective, if the input's message is supposed to change in future runs it's better to use a variable and probably a function.