-2

I would like to include the user's response to 'age' in the answer.

However, including 'age' returns an error. Seems to be because it is preceded by float. Is there a way to include the response to 'How old are you?'?

Here's the code:

name = input("What is your name? ")
age = float(input("How old are you? "))
answer1 = (age + "!? That's very old, " + name + "!")
answer2 = (age + "? You're still young, " + name + ".")
if age > 60:
    print(answer1)
if age < 60:
    print(answer2)
Vadim Kotov
  • 8,084
  • 8
  • 48
  • 62

2 Answers2

2

Unlike e.g. Java, Python does not automagically call the __str__ method when concatenating objects some of which are already strings. The way you do it, you would have to convert it to a string manually:

answer1 = (str(age) + "!? That's very old, " + name + "!")

Consider, however, using proper string formatting in the first place:

answer1 = ("{age}!? That's very old, {name}!".format(age=age, name=name))
user2390182
  • 72,016
  • 6
  • 67
  • 89
  • Thank you very much for the answer. Is there a way to remove the .0 that this adds to the print response? I'm seeing: "65.0!? That's very old..." – ukraineinthemembrane Sep 28 '17 at 11:24
  • Yes, you can use e.g. `{age:.0f}`. Read the string [formatting docs](https://docs.python.org/2/library/string.html#format-string-syntax) for more info. – user2390182 Sep 28 '17 at 11:26
0

You have a few options here.

  1. Convert age to string:

    answer1 = (str(age) + ...)

  2. Use old-style string formatting:

    answer1= "%f!? That's very old, %s!" % (age, name)

  3. Use Python 3.6's excellent string interpolation:

    answer1 = f"{age}!? That's very old, {name}!"

I would go with the third.

zmbq
  • 38,013
  • 14
  • 101
  • 171
  • There's also a forth way, using `format`, but I never liked it, especially now that string interpolation is available. – zmbq Sep 28 '17 at 11:21
  • Why don't you like it? `format` is the recommended way before Python3.6. Unlike interpolation, it is available in all Python versions and its usage seems more natural to me than the old-style formatting. – user2390182 Sep 28 '17 at 11:30
  • I guess it's my roots in C. Never liked it, never cared enough to convince others not to like it. – zmbq Sep 28 '17 at 18:47