[Tutor] How do I call a variable within an input () function?

Steven D'Aprano steve at pearwood.info
Fri Feb 6 08:28:11 CET 2015


On Thu, Feb 05, 2015 at 05:57:06PM -0600, Edgar Figueroa wrote:

> Hello group.  I'm trying to call the variable "name" within my input () function.
> Here's what I have:
> name = input("Hello. What's your name? ")

*Your* input function? Is that different from the standard input 
function?

Are you using Python 2 or Python 3, because the standard input function 
is different between the two. You should use input() is Python 3, but 
raw_input() in Python 2.

> print("\nHello", name, ". Nice to meet you.")
> favFood1 = input("\n", name, ", what's your favorite food? ")
> Obviously it isn't working.  It tells me I have too many arguments for the input () function.  Basically, I want the output to read as follows:

Nothing is "obvious" in programming :-)

Rather than summarise the error, please copy and paste the full 
traceback:

py> input("Frank", "what's your favourite food?")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: input expected at most 1 arguments, got 2

If you are talking about the standard input function in Python 3, then 
you need a single string argument. You have two strings (ignoring the 
"\n" which is unneeded). How do you get one string from two?

Here are four ways:

py> name = "Frank"
py> name + ", what's your favourite food?"  # String concatenation.
"Frank, what's your favourite food?"

py> "%s, what's your favourite food?" % name  # String interpolation.
"Frank, what's your favourite food?"

py> "{}, what's your favourite food?".format(name)  # format method.
"Frank, what's your favourite food?"


py> from string import Template  # String templating.
py> tmpl = Template("$name, what's your favourite food?")
py> tmpl.safe_substitute(name=name)
"Frank, what's your favourite food?"


Take your pick, for this case they will all be about as good as the 
others. I would normally choose % interpolation.


-- 
Steve


More information about the Tutor mailing list