1

Why does this function print arg1 arg2 instead of Hello world? Shouldn't arg be equal to the arguments arg1 and arg2 and then be used in print()?

def printer(arg1, arg2):
    for i in range(2):
        arg = 'arg{} '.format(str(i+1))
        print(arg, end="")

printer('Hello', 'world')
Stephen Rauch
  • 44,696
  • 30
  • 102
  • 125
Setti7
  • 151
  • 4
  • 15
  • 2
    A string containing the name of a variable is not the variable. It "doesn't work" because it's wrong. That is to say, it works fine; it does exactly what you told it to do. – kindall Feb 05 '18 at 03:08
  • It's not at all clear that this is an appropriate duplicate. OP is clearly interested in why Python doesn't recognize strings as symbols. – Joshua R. Feb 05 '18 at 03:23

3 Answers3

1

You are trying to print strings, not your arguments. If you need to iterate through your function arguments, you can do something like this:

Code:

def printer(*args):
    for arg in args:
        print(arg, end="")

printer('Hello', 'world')

Results:

Helloworld
Stephen Rauch
  • 44,696
  • 30
  • 102
  • 125
1

You can use locals() to access current local scope:

def printer(arg1, arg2):
    for i in range(2):
        arg = 'arg{}'.format(str(i+1))
        print(locals().get(arg), end="")

printer('Hello', 'world')
Sraw
  • 17,016
  • 6
  • 45
  • 76
-1

@kindle is right. You're making a string variable. And Stephen Rauch's answer is the a better way to accomplish what you want.

However, Python can be made to evaluate a string as code using the eval function. You could get the effect you expected by changing

print(arg, end="")

to

print(eval(arg), end="")
Joshua R.
  • 2,262
  • 1
  • 17
  • 21