1

I'm trying to follow along with a book and it says to put in the following code but it's not working.

The book is: Matthes, Eric. Python Crash Course, 2nd Edition (p. 21). No Starch Press. Kindle Edition.

first_name = "ada"
last_name = "lovelace"
full_name = f"{first_name} {last_name}"
print(full_name)

Error:

 line 3
    full_name = f"{first_name} {last_name}"
                                          ^
SyntaxError: invalid syntax

It is in Python 3.7.3 according to terminal so that's not the issue

B. Go
  • 1,436
  • 4
  • 15
  • 22
  • 4
    This syntax (f-strings) exists only since Python 3.6. You must be running an older version. – Thierry Lathuille Sep 23 '19 at 20:42
  • 2
    Your code looks fine and runs on my machine using Python 3.6.3. You should double check which version of Python is running. See [this question](https://stackoverflow.com/questions/1093322/how-do-i-check-what-version-of-python-is-running-my-script) for how to do so. – Chris Mueller Sep 23 '19 at 20:45
  • 3
    Try `import sys; print(sys.version)` to check which version you are really running. – Thierry Lathuille Sep 23 '19 at 20:48
  • Don't believe the terminal check `sys.version` to be sure. – Barmar Sep 23 '19 at 21:00
  • Your code runs fine under Python 3.6+. Please add the suggested code as first line of your script and run it again - and comment out the line with the error... – Thierry Lathuille Sep 23 '19 at 21:00

2 Answers2

1

In 3.7.3, you could alternatively use .format() like this:

first_name = "ada"
last_name = "lovelace"
full_name = "{} {}".format(first_name, last_name)
print(full_name)

I hope this helps

Jack Hanson
  • 336
  • 1
  • 2
  • 11
  • 1
    Well, no, you don't need to use `format`. The code given by the OP in the question if perfectly valid and runs fine on any version of Python >= 3.6. – Thierry Lathuille Sep 23 '19 at 21:05
  • Thanks for pointing that out. I altered my answer to say "alternatively", because it is another way to get the answer that OP needed – Jack Hanson Sep 23 '19 at 21:12
1

There are several other ways to achieve the same result, but the code you gave is valid on python 3.6 and above. It's likely that you are running an older version, even if the terminal doesn't say so. You can reliably check this with

import sys
print (sys.version)

There are other ways to get the same result, I'll list a few below.

first_name = "john"
last_name  = "doe"

full_name_m1 = first_name + " " + last_name
full_name_m2 = first_name + " %s" % last_name
full_name_m3 = "%s %d" % (first_name, last_name)

full_name_m4 = " "
for i in first_name:
    full_name_m4 += first_name[i]
full_name_m4 += " "
for i in last_name:
    full_name_m4 += last_name[I]

Sorry for formatting or typos, I'm on a mobile mobile. The last examples are definitely overkill, but seeing as you're learning python they might be interesting.

36bitavi
  • 11
  • 2