gragr
(Rahul Garg)
February 20, 2024, 6:17am
1
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.
MegaIng
(Cornelius Krupp)
February 20, 2024, 6:31am
2
You need to use ```
, not '''
otherwise the formatting will not work. Because of this, I can’t really tell what is going wrong.
Rosuav
(Chris Angelico)
February 20, 2024, 6:32am
3
Rahul Garg:
TypeError: str returned non-string (type NoneType)
File “Class_Trial.py”, line 6
return print(self.a)
Please guide as to what mistake i’m doing.
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
gragr
(Rahul Garg)
February 20, 2024, 6:33am
4
Thanks for correcting me.
gragr
(Rahul Garg)
February 20, 2024, 6:38am
5
Thanks for correcting me.
MegaIng
(Cornelius Krupp)
February 20, 2024, 6:43am
6
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 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?
Stefan2
(Stefan)
February 20, 2024, 7:33am
9
Please format the error message as a code block, too, so we can see it more clearly, particularly what the ^
points at.
Stefan2
(Stefan)
February 20, 2024, 7:35am
10
And add this at the top of your code and tell us the output:
import sys
print(sys.version)
gragr
(Rahul Garg)
February 20, 2024, 8:14am
11
Version shown is
2.7.18 (v2.7.18:8d21aa21f2, Apr 20 2020, 13:25:05) [MSC v.1500 64 bit (AMD64)]
gragr
(Rahul Garg)
February 20, 2024, 8:17am
13
It seems to be a version issue.
If i try the same code in Version 3.11 then it is working.
kknechtel
(Karl Knechtel)
February 20, 2024, 8:17am
14
Rahul Garg:
Version shown is
2.7.18
Yes; this means that
Rahul Garg:
I’m using Version 3.11
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.
Rahul Garg:
MSC v.1500
This part tells me you are using Windows, so see these links for guidance:
2 Likes
gragr
(Rahul Garg)
February 20, 2024, 8:19am
15
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 ??
bschubert
(Brian Schubert)
February 20, 2024, 1:45pm
16
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.