Search code examples
pythonraw-input

Utilizing %r within raw_input in python


Is it feasible to utilize %r within raw_input in python?

For context, I'm working on Zed Shaw's Exercise 12. (Great resource! The lessons are very helpful, and well paced.)

I'm playing around in the extra credit, trying to get raw_input to repeat what I typed in. I know I can accomplish the same thing with a print statement, but am curious if I can accomplish it within raw_input.

The code I'm typing is:

from sys import argv

script, firstname, lastname = argv

age = raw_input("Hello %r, what is your age? ") % firstname

print ("Ahh, Mr. %r, you are %r years old.") % (lastname, age)

The error I get is:

Traceback (most recent call last):
  File "ex13a.py", line 5, in <module>
    age = raw_input("Hello %r, what is your age? ") % firstname
TypeError: not all arguments converted during string formatting

Thanks in advance!


Solution

  • Your line should read

    raw_input("Hello %r, what is your age? " % firstname)
    

    instead of

    raw_input("Hello %r, what is your age? ") % firstname
    

    Otherwise, you would not format your "Hello %r, ..." string, but the resulting string of the call to raw_input.