[Tutor] How to use a Variable in an input statement

Mats Wichmann mats at wichmann.us
Wed Jul 1 10:13:08 EDT 2020


On 7/1/20 7:37 AM, Alan Gauld via Tutor wrote:
> On 01/07/2020 13:42, YAW ANTWI-ADJEI wrote:
> 
>> Thus, I want something like:
>> *StudentName* = 'Yaw'
>> Age = input(*StudentName*, 'how old are you?')
> 
> There are several ways to do this, but string formatting is
> probably best:
> 
> age = input("{} how old are you? ".format(Studentname))
> 
> OR
> 
> age = input("%s how old are you? " % StudentName)
> 
> Or even, in recent pythons(post 3.6):
> 
> age = input(f"{StudentName} how old are you? ")
> 
> The last one is preferred if you don't have to support older versions.

To expand:

input takes a single string argument, so build the string as you wish.
You can do it inline, as above, or separately, like:

age_prompt = f"{StudentName}: how old are you? "
age = input(age_prompt)

Also reminder: input returns a string.  Don't treat the return as
anything else (e.g. an integer) until you've converted it - and
normally, you also want to "validate" the contents of any external data
source before using it or you risk surprises (at best) or serious Bad
Things (at worst).




More information about the Tutor mailing list