class Student(object):
def__init__(self, name='', school='', grade=''): #This is where I get the error
if not name:
name = raw_input('what is the student\'s name: ')
if not school:
school = raw_input('What is the studnet\'s school: ')
if not grade:
grade = self.get_grade()
self.name = name
self.school = school
self.grade = grade
self.print_student()
def get_grade(self):
while True:
grade = input('What is the student\'s grade: [K, 1-5]')
if grade.lower() not in ['k','2','3','4','5']:
print('I\'m sorry, but {} isn\'t valid.'.format(grade))
else:
return grade
def print_student():
print('Name: {}'.format(self.name))
print('School: {}'.format(self.school))
print('Grade: {}'.format(self.grade))
def main():
student1 = Student()
studnet2 = Student(name='Bethmi Amalya', grade = '5', school= 'Visakha Vidyalaya')
if __name__ == '__main__':
main()
2 Answers
you have 2 issues in code :
1 . def__init__(.... , there should be a space between def keyword and init( i.edef __init__(...
2 . self should be passed to def print_student() i.e print_student(self): and all variable accesses should be with self e.g self.name etc in print_student function .
class Student(object):
def __init__(self, name='', school='', grade=''): #This is where I get the error
if not name:
name = raw_input('what is the student\'s name: ')
if not school:
school = raw_input('What is the studnet\'s school: ')
if not grade:
grade = self.get_grade()
self.name = name
self.school = school
self.grade = grade
self.print_student()
def get_grade(self):
while True:
grade = raw_input('What is the student\'s grade: [K, 1-5]')
if grade.lower() not in ['k','2','3','4','5']:
print('I\'m sorry, but {} isn\'t valid.'.format(grade))
else:
return grade
def print_student(self):
print('Name: {}'.format(self.name))
print('School: {}'.format(self.school))
print('Grade: {}'.format(self.grade))
def main():
student1 = Student()
studnet2 = Student(name='Bethmi Amalya', grade = '5', school= 'Visakha Vidyalaya')
if __name__ == '__main__':
main()
2 Comments
Gayathra Ranasinghe
Thank you so much :) It worked. still new to prgramming
toheedNiaz
keep it up :) happy coding
In line 1: def__init__(self, name='', school='', grade=''):
There is no space between
defand__init__Add a space to fix the syntax error.
Also:
Python 2 used raw_input()
Python 3 uses input()
def __init__instead ofdef__init__Happy Coding!