-2

I have my function defined:

def somme(n1 , n2):
  result = (n1 + n2)
  return (f"The sum of" {n1} "+" {n2} "is equal to" {result})

That I call like this:

somme(1,1)

I get error on {n1}:

return (f"The sum of" {n1} "+" {n2} "is equal to" {result})
                          ^
SyntaxError: invalid syntax
Jorge Luis
  • 813
  • 6
  • 21
Leao
  • 1

3 Answers3

0

f-strings are string literals that have an f at the beginning and curly braces containing expressions that will be replaced with their values. More information

def somme(n1 , n2):
  result = (n1 + n2)
  return (f"The sum of {n1} {n2} is equal to {result}")
shahidammer
  • 1,026
  • 2
  • 10
  • 24
0

You're constructing your f-string wrongly. Just do this:

def somme(n1, n2):
    return f'The sum of {n1} + {n2} is equal to {n1+n2}'
DarkKnight
  • 19,739
  • 3
  • 6
  • 22
0

In Python a string ends when the closings quotes are found. So when you write:

"The sum of" "3 + 4"

you are writing two different strings.

Format strings (fstring) substitute every variable between braces inside the string. Your fstring does not even see what happens when the quotes are closed. If you want to have your variable in your string you just write:

f"The sum of {n1} + {n2}"

Notice that {n1} and {n2} are both inside your string.

What you wrote is a fstring without any braces, so no substitution is performed. So you have a plain string that closes and just after that a variable between braces (that would be a set). A string, space, a set: that means nothing in Python. Notice that the error is not pointing to your variable: it is pointing the first place the interpreter realizes that your code is not valid.

Your particular case will be like this:

f"The sum of {n1} + {n2} is equal to {result}"
Jorge Luis
  • 813
  • 6
  • 21