0

I'm somewhat new to python and am working on an assignment with a friend for school. We wanted to ask for a swimmer's name, followed by asking what time they managed to achieve. We wanted the program to work like this:

Name = input('Input swimmers name: ')
Time = int(input('What time did',Name,'achieve? ')

However it isn't working. What could we use here that will allow us to ask the swimmer's time by using the swimmer's name in the question?

1
  • 1
    'foo' + Name + 'bar' Commented Aug 23, 2016 at 8:42

2 Answers 2

3

You have to pass a single string to input, you can do it by first concatenating your 3 strings:

Time = int(input('What time did' + Name + 'achieve? ')

BTW: "achieve" with an "e" ;-)

Sign up to request clarification or add additional context in comments.

4 Comments

You could also use: Time = int(input('What time did {} acheive? '.format(Name)). I also wouldn't use int() there, in case someone inputs 0:56.15 or something.
Thanks for that man, Im super surprised at how fast this was answered.
@Andrew this is actually slower: see my comment in other answer.
@JulienBernu Interesting. I find the format syntax more readable, but good to know that the alternative is faster if I ever have to optimise.
2

You can also use %s for concatenation

Time = int(input('What time did %s achive? ' % Name ))

3 Comments

If you want your answer to be better you can back up your "is faster than +" with some source :)
Especially when it is wrong... %timeit 'What time did %s achive? ' % "toto" 10000000 loops, best of 3: 99 ns per loop but %timeit 'What time did ' + 'toto' + ' achive?' 10000000 loops, best of 3: 38.8 ns per loop (Note that I'm not the downvoter ;-) and for completeness: %timeit 'What time did {} acheive? '.format('toto') 1000000 loops, best of 3: 204 ns per loop
Thanks @grael, Julien for this. Have corrected. learnt something.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.