Syntax Error for __str__ function

Hi. I’m beginner to python Coding.
I’m practicing for “Class” in python.

I have below code,

class trial:
	def __init__(self,a,b):
		self.a = a
		self.b = b
	def __str__(self):
		return f"{self.a}"
	def myfunc(self):
		print("Hi")

x = trial(4,5)
print(x)
x.myfunc()

File "NewTextDocument.py", line 6
    return f"{self.a}"
                     ^
SyntaxError: invalid syntax

On execution i’m getting error,

Please guide as to what mistake i’m doing.

You need to use ```, not ''' otherwise the formatting will not work. Because of this, I can’t really tell what is going wrong.

That didn’t come from the code you posted. Make sure you post the actual code you are running, not a different version of it.

1 Like

Thanks for correcting me.

Thanks for correcting me.

What version of python are you using? f-strings were added in 3.6, if you have an older version, you should upgrade your python.

1 Like

I’m using Version 3.11

I pasted the code you gave into Python and it ran as intended, no syntax error. Are you sure you don’t have any typos in your actual code that didn’t make it into the version we’re seeing?

Please format the error message as a code block, too, so we can see it more clearly, particularly what the ^ points at.

And add this at the top of your code and tell us the output:

import sys
print(sys.version)

Version shown is

2.7.18 (v2.7.18:8d21aa21f2, Apr 20 2020, 13:25:05) [MSC v.1500 64 bit (AMD64)]

It seems to be a version issue.

If i try the same code in Version 3.11 then it is working.

Yes; this means that

is mistaken.

There is more than one Python on your system. There are good reasons to keep this, but you must therefore understand, how to tell your computer which one to use.

This part tells me you are using Windows, so see these links for guidance:

2 Likes

Awesome. Thank you all for clearing my doubts and resolving the error.

Is there a way to mark the correct solution for my post and close it ??

There’s no built-in way to do that (but there’s been some discussion about enabling a similar feature).

For now you can try editing the the title and/or liking the posts you found helpful.