Why does my main program default to the except?

Question:

Could you possibly check my syntax and tell me why the debugger skips my try statement and skips to the except.

book class:

class book(object):
    
    def _init_(self, title, author, numPages):
        if title is None:
            raise ValueError("invalid 'title' argument. please try again")
        if author is None:
            raise ValueError("invalid 'author' argument. please try again")
        if numPages <= 0:
            raise ValueError("invalid 'numPages' argument. please try again")
        
        self.title = title
        self.author = author
        self.numPages = numPages

main class:

from book import book

def printBook (b):
    if b is None:
        raise ValueError('invalid book argument')
    print (b.author + ": " + b.title + "n" +" Number of page: " + b.numPages )

if __name__ == '__main__':
    try: 
        b1 = book("The Eye of the World", "Robert Jordan", 685)
        b2 = book("The Heir of Novron", "Michael J. Sullivan", 932)
        
        printBook(b1)
        printBook(b2)
        
    except:
        print("ERROR: INVALID BOOK")
Asked By: Justin Moon

||

Answers:

There are at least 2 mistakes:

  1. Constructor is called __init__ as jonsharpe already mentioned

  2. you need str() for concatenation of ints and string. So you need to modify your print function:

    print (b.author + ": " + b.title + "n" +" Number of page: " + str(b.numPages) )
    
Answered By: Peter Parker
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.