如果在Python 3.7中不需要,可以跳过一个条件?

问题描述 投票:1回答:1

我用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个回答
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")
© www.soinside.com 2019 - 2024. All rights reserved.