如果 Python 3.7 不需要,如何跳过一个条件?
How to skip one condition if that is not needed in Python 3.7?
我使用 if, try/except 子句编写了代码。我想使用 "try" 检查参数是否正确,如果正确,"print" 函数将 运行。
如果参数不对则打印错误信息并且打印部分不会运行。
问题是当我输入正确时它是 运行ning 但是当我输入错误时,打印错误消息后我得到 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)
您的打印应该在代码的 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")
我使用 if, try/except 子句编写了代码。我想使用 "try" 检查参数是否正确,如果正确,"print" 函数将 运行。 如果参数不对则打印错误信息并且打印部分不会运行。 问题是当我输入正确时它是 运行ning 但是当我输入错误时,打印错误消息后我得到 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)
您的打印应该在代码的 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")