0

I am currently on Week 8 Object Oriented Programming of CS50P

This is with regards to an example given during the lecture at about 1:58:40, where we are suppose to use Try-Except to handle the ValueError raised.

However, I believe I did not catch the error correctly.

name:jack
course:accountancy
name:jack
course:biz

If i input the above into the terminal it returns the following error:

AttributeError: 'NoneType' object has no attribute 'name'

name:jack course:accountancy name:jack course:biz

class Student:
    def __init__(self, name, course):
        if not name:
            raise ValueError("missing name")
        if course not in ["biz", "cs"]:
            raise ValueError("invalid course")
        self.name = name
        self.course = course

def main():
    student = get_student()
    print(f"{student.name} from {student.course}")

def get_student():
    name = input("name:")
    course = input("course:")
    try:
        return Student(name, course)
    except ValueError:
        get_student()


if __name__ == "__main__":
    main()

Any help will be greatly appreciated

1 Answer 1

0

I tried to solve the problem and found out that the program should try to re-prompt the user for the name and course until both of them are right and you should include the name and course input statements in the "try:"

So, here is my version of the program:

class Student:
    def __init__(self, name, course):
        if name=="":
            raise AttributeError("No name given")
        if course not in ["biz", "cs"]:
            raise AttributeError("No course given")
        self.name = name
        self.course = course
    


def main():
    std=get_student()
    print(f"{std.name} from {std.course}")

def get_student():
    while True:
        try:
            name = input("name:")
            course = input("course:")
            return Student(name, course)
        except AttributeError:
            continue


if __name__ == "__main__":
    main()

Thank You.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .