如何在python中处理AssertError

我有一个名为newSong的文本字符串,其中包含两个instancevariabel(标题,艺术家),如下所示:

newSong = Song ("Rum and Raybans","Sean Kingston and Cher Lloyd")

我有一个名为checkIfArtistExists(self,artist)的方法。我的任务是使用split,for循环和if语句。我必须拆分艺术家,所以如果艺术家的名字由肖恩,金斯顿,雪儿,劳埃德组成,它将返回true,否则返回false。

我收到assertError:

>>> assert(not newSong.checkIfArtistExsists("Sadley"))       # False
AssertionError

我是编程新手,逻辑也不是很好。有人可以给我建议或建议吗?

class Songs(object):

   def __init__(self,tittel,artist):

        #Instanse variabler

        self._tittel = tittel

        self._artist = artist

  def  CheckIfArtistExists(self,artist):


       names = artist.split()

       for n in names:
           if n in artist:
              return true
           else:
             return false

newSong = Song ("Rum and Raybans","Sean Kingston and Cher Lloyd")

assert(newSong.CheckIfArtistExists("Sean Kingston and Cher Lloyd"))
assert(not newSong.CheckIfArtistExists(""Sadley"")) #False
thickice_1119 回答:如何在python中处理AssertError

您正在针对自己而不是实例变量artist测试_artist参数。这就是为什么newSong.checkIfArtistExists("Sadley")应该为False时为True。

一旦找到匹配项,您的循环就会退出。它应该等待直到测试完所有拆分部分都是子字符串。

def CheckIfArtistExists(self,artist):

   names = artist.split()

   for n in names:
       if n not in self._artist:
          return False
   return True
本文链接:https://www.f2er.com/3157657.html

大家都在问