Reputation:
I am working on a project that requires me to use str to print out as an answer. When I run this code, the compiler gives syntax error by pointing out to return statement. I would love to get help to fix this problem.
I tried to removing parentheses around the return code.
import random
class Movie:
def __init__ (self, title, year, drname, cat, length):
self.title = title
self.year = year
self.drname = drname
self.cat = cat
self.length = length
def __str__(self):
return (self.title + '('self.cat','+ self.year')' +'directed by ' + self.drname + ', length ' + self.length + 'minutes')
#Apollo 13 (Drama, 1995) directed by Ron Howard, length 140 minutes
#It should be printed out as shown above
mv1 = Movie("Apollo 13", 1995, 'Ron Howard', 'Drama', 140)
Upvotes: -1
Views: 85
Reputation: 3735
You should format the returned value of __str__
using f-string (PEP498):
f"{self.title}({self.cat},{self.year}) directed by {self.drname}, length {self.length} minutes"
Your code, PEP8 and working:
class Movie:
def __init__(self, title, year, drname, cat, length):
self.title = title
self.year = year
self.drname = drname
self.cat = cat
self.length = length
def __str__(self):
return f"{self.title} ({self.cat}, {self.year}) directed by {self.drname}, length {self.length} minutes"
# Apollo 13 (Drama, 1995) directed by Ron Howard, length 140 minutes
# It should be printed out as shown above
mv1 = Movie("Apollo 13", 1995, 'Ron Howard', 'Drama', 140)
print(mv1)
Output:
Apollo 13 (Drama, 1995) directed by Ron Howard, length 140 minutes
Upvotes: 1
Reputation: 15172
Beside the other answer answers, I recommend using f-strings (introduced with python 3.6) for string formating:
return f"{self.title} ({self.cat}, {self.year}) directed by {self.drname} , length {self.length} minutes"
Upvotes: 4
Reputation: 1322
Your code states '('self.cat','+ self.year')'
without a +
.
Use '(' + self.cat + ',' + self.year + ')'
instead.
Also, you may want to consider a space between the category and year. If so, use the following:
'(' + self.cat + ', ' + self.year + ')'
In addition, your year
and length
need to converted to a string, for example using str(self.length)
.
Upvotes: 1
Reputation: 169
just a small syntax error, the plus (+) sign is missing in your return statement.
return (self.title + ' (' + self.cat + ', ' + self.year + ') ' + 'directed by ' + self.drname + ', length ' + self.length + ' minutes.')
This should work.
Upvotes: 1