How to make an addition operetion using f-strings?

Hello everyone, python newbie here.

Just started learning python and been wondering if I can make addition operations using f-string.
Learned about f-strings with this example:
name = “John”
age = 23
cash = 50
f"{name} is {age} years old and has {cash} bucks on his pocket."

But if I try to use:
n1 = input(“First number:”)
n2 = input(“Second number:”)
f"The result is {n1}+{n2}"
Then I just get an “invalid syntax” error. Been trying to fiddle around with it but everything end up way too long for my taste, and feels kinda weird because the f-string was supposed to make everything compact, right?

I appreciate any help on this matter. Thanks for your time!

Remeber that, by default, any input will return a string. So either convert numbers at the input or before any calculations.

I prefer to be a little more verbose when naming variables: intN1 intN2 for example and assign correctly, as in intN1 = int(input("First number: "))

n1 = input("First number:")
n2 = input("Second number:")
print(f"The result of {n1}+{n2} is",int(n1)+int(n2))

# or...

n1 = int(input("First number:"))
n2 = int(input("Second number:"))
print(f"The result of {n1}+{n2} is",n1+n2)
1 Like

@rob42 Thank you very much for the help and the tips! Much appreciated!!

No worries; glad to be of help.

One more tip: numbers as a string are fine if you don’t plan on using them for calculations, as in your example age = 23, but again, I’d be a little more verbose: strAge = '23'. The reason being that when you get a script that is 100s of lines in length, it can be of help to know how a variable has been assigned, simply by how it’s been named.

1 Like

That works, but the calculation and the subsequent formatting of the sum occur outside the bounds of the f-string.

The following includes the calculation and the formatting of the entire output within the f-string:

print(f"The result of {n1} + {n2} is {n1 + n2}.")
1 Like

Sorry, I see. Yes that’s better.

@Airaneon
The example given by @Quercus answers your question more precisely than mine.

I’m still ‘old school’ with strings and as such I’m leaning this also.

This is quite a good read on the topic:

2 Likes

The code you show works for me. It doesn’t give a SyntaxError:

Your code:

n1 = input("First number:")
n2 = input("Second number:")
f"The result is {n1}+{n2}"

If I enter 2 and 3 at the prompts, I get the result:

‘The result is 2+3’

If you are getting a SyntaxError, whatever code you are running is not the same as the code you showed us.

You’re onto something, @steven.daprano, and I think I found the issue; I pasted the OP code into Brython and got a syntax error.

OP code:

n1 = input(“First number:”)
n2 = input(“Second number:”)
f"The result is {n1}+{n2}"

Code from your post:

n1 = input("First number:")
n2 = input("Second number:")
f"The result is {n1}+{n2}"

The OP code has slanted double quotes. Your quotes are vertical. The code formatter coloring discloses it (at least on Discourse Mobile).

So the problem is either in an interpreter or the editor used by the OP.

@Airaneon, what editor and interpreter are you running?

P.S. This is why you should ALWAYS paste the error message (as text, not a screenshot) and use the code formatting controls shown HERE and HERE.

And this is why is it absolutely critical to always post the full error message.

Using curly quotes, Python 3.10 points to exactly where the error is, and tells you the problem:


>>> n1 = input(“First number:”)

  File "<stdin>", line 1

    n1 = input(“First number:”)

               ^

SyntaxError: invalid character '“' (U+201C)

Python only uses plain old “typewriter quotes”, not fancy curly quotes.

I was using Pycharm. Apologies for not posting the full error, honestly I did not pay attention if it had a code afterwards or not. The code I posted was exactly the same that I was using, issue is I didn’t write “print” before the third line, because I was following a book example trying to adapt my code to it. But Rob helped me out with it and gave me some tips to prevent some future issues.

Your computer is automatically generating curvy quotes by default, Bruno. Find out where they’re coming from and disable that “feature” or it will cause you constant headaches when programming. The “print” in the quote above has curvy quotes and your first code sample also has them in the line name = "John".

If you like the curvy quotes and need/want to keep them…
PyCharm is evidently following the curvy quotes setting. You might try VS Code to see if it produces “typewriter” quotes in the code editor. You could also try Notepad++ but that’s less ideal than the first two. (VS Code is great; I changed from PyCharm quickly after trying VS Code.)

Glad you got the help you were looking for, Bruno. I can’t say that I would have noticed a missing ‘print’ function (and it doesn’t look like print() was actually your problem), but I can say that the default message body font makes errors MUCH harder to see. You’ll do everyone a big favor–especially yourself–if you fence your posted code with backtics like this:

```python
<code goes here>
```

P.S. The fstring code ran fine without the print. I haven’t yet read the docs.python.org on fstrings but this post at RealPython shows the same syntax you used in your posted code. That is, it also omits the print instruction.

If you do use print, you need to enclose your print() arguments in parentheses as shown below.

>>> n1 = input("First number:")
>>> n2 = input("Second number:")
f"The result is {n1}+{n2}"
'The result is 1+2'

>>> print (f"The result is {n1}+{n2}")
The result is 1+2

>>> print f"The result is {n1}+{n2}"
  File <Javascript undefined>, line 1
    print f"The result is {n1}+{n2}"
          ^
SyntaxError: missing parenthesis in call to 'print'
>>> 

Notice the caret ( ^ ⟩. It points to exactly where the error message was triggered*. As you continue your Python journey, get good at reading the error messages and you’ll be able to work problems out quicker (and without having to wait for an answer on a forum :slightly_smiling_face:).

* The error message refers to Javascript because I ran the code in Brython, a Python interpreter written on Javascript so that it runs in a browser.

If you’d like some simple practice, run your name = “John” line as-is with the curly brackets and read the full error code.

1 Like

Thanks for bringing it to my attention, but it seems that the curvy quote only happen in this forum. Everywhere else is fine, so thankfully it won’t be a future issue.

Thanks for this tip, I’ll definitely pay attention to it from now on!