【问题标题】:How to skip one condition if that is not needed in Python 3.7?如果 Python 3.7 中不需要,如何跳过一个条件?
【发布时间】:2019-02-18 00:39:33
【问题描述】:

我编写了一个使用 if、try/except 子句的代码。我想用“try”来检查参数是否正确,如果正确,“print”函数就会运行。 如果参数不正确,则将打印错误消息并且打印部分将不会运行。 问题是当我输入正确时它正在运行,但是当我输入错误时,在打印错误消息后我得到 NameError,说“room1”没有定义。我明白为什么会这样,但我很困惑如何在不出错的情况下获得正确的输出。

我的代码是:

class Hotel:
    def __init__(self,room,catagory):
        if type(room) != int:
            raise TypeError()
        if type(catagory) != str:
            raise TypeError()
        self.room = room
        self.catagory = catagory
        self.catagories = {"A":"Elite","B":"Economy","C":"Regular"}
        self.rooms = ["0","1","2","3","4","5"]


    def getRoom(self):
        return self.room

    def getCatagory(self):

        return self.catagories.get(self.catagory)
    def __str__(self):
        return "%s and %s"%(self.rooms[self.room],self.catagories.get(self.catagory))

try:
    room1 = Hotel(a,"A")

except: 

    print("there's an error")


print (room1)

【问题讨论】:

    标签: output nameerror python-3.7


    【解决方案1】:

    您的打印应该在代码的try 段中,因为无论是否有错误,它都会执行。

    class Hotel:
        def __init__(self,room,catagory):
            if type(room) != int:
                raise TypeError()
            if type(catagory) != str:
                raise TypeError()
            self.room = room
            self.catagory = catagory
            self.catagories = {"A":"Elite","B":"Economy","C":"Regular"}
            self.rooms = ["0","1","2","3","4","5"]
    
    
        def getRoom(self):
            return self.room
    
        def getCatagory(self):
    
            return self.catagories.get(self.catagory)
        def __str__(self):
            return "%s and %s"%(self.rooms[self.room],self.catagories.get(self.catagory))
    

    初始化

    try:
        room1 = Hotel(a,"A")
        print (room1)
    except: 
        print("there's an error")
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-05-17
      • 1970-01-01
      • 2017-02-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-11-18
      • 1970-01-01
      相关资源
      最近更新 更多