类练习问题中的Python语法错误



我正在尝试一些练习问题,以了解更多关于Python中类的信息,在运行此代码时,我在第11行(print(f"The restaurant's name is: {self.restaurant_name}. The restaurant serves: {self.cuisine_type}.")(遇到语法错误。我一遍又一遍地检查我的代码,但没有成功地找到问题的解决方案,我想知道是否有人能帮我找出问题所在。我还尝试过从类中删除describe_restaurant方法,只保留open_restaurant方法,但我仍然收到语法错误,但现在它在第15行。我试图在另一个问题论坛上找到这个问题的答案,但我找不到任何对我有用的东西。我是一个新手程序员,所以如果我在代码中犯了一个愚蠢的错误,我很抱歉。谢谢

class Restaurant:
"""A simple attempt to model a restaurant."""
def __init__(self, restaurant_name, cuisine_type):
"""Initialize restaurant name and cuisine type attributes."""
self.restaurant_name = restaurant_name
self.cuisine_type = cuisine_type
def describe_restaurant(self):
"""Give a brief description of the restaurant."""
print(f"The restaurant's name is: {self.restaurant_name}. The restaurant serves: {self.cuisine_type}.")
def open_restaurant(self):
"""Display a message that the restaurant is open."""
print(f"{self.restaurant_name} is open!")
restaurant = Restaurant('Hard Rock Cafe', 'American Grub')
print(f"{restaurant.restaurant_name} serves {restaurant.cuisine_type}.")
restaurant.describe_restaurant()
restaurant.open_restaurant()
print(f"The restaurant's name is: {self.restaurant_name}. The restaurant serves: {self.cuisine_type}.")
                               ^
SyntaxError: invalid syntax

您运行的是旧版本的python:

f-string在python上的工作>=3.6版本请参阅pep-python pep498 f-stringpython2.7

a  = 12345
print(f"python2.7 don't support f-strint {a}")
File "<stdin>", line 1
print(f"python2.7 don't support f-strint {a}")
^
SyntaxError: invalid syntax

python3.8

a = 12345                                                                                                                                                                                          
print(f"but on python >3.6 f-strinf work {a}")                                                                                                                                                     
but on python >3.6 f-strinf work 12345

检查您的python版本f适用于python 3.6及以上版本所以它在python2中不起作用

如果您仍在使用python2,请从更改打印语句字符串格式

print(f"{restaurant.restaurant_name} serves {restaurant.cuisine_type}.")

print(" {} serves {} " .format(restaurant.restaurant_name,restaurant.cuisine_type))

最新更新