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
  • 47,830
  • 31
  • 106
  • 135
Setti7
  • 149
  • 4
  • 16
  • 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
  • 47,830
  • 31
  • 106
  • 135
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
  • 18,892
  • 11
  • 54
  • 87
-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,282
  • 1
  • 18
  • 21