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

2024-09-29 01:30:00 发布

您现在位置: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

Tags: the方法代码nameselfisdeftype
3条回答

检查您的python版本 f是为Python3.6及更高版本引入的 所以它在python2中不起作用

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

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

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

您正在旧python版本上运行:

python上的f字符串工作>;=3.6版本 见政治公众人物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

相关问题 更多 >