我收到此错误:SyntaxError:语法无效

时间:2018-04-21 19:34:49

标签: python python-3.x syntax

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 个答案:

答案 0 :(得分:3)

您在代码中有2个问题:

1。 def__init __(....,def关键字和 init 之间应该有一个空格( 即def __init__(...

2。 self应传递给def print_student(),即print_student(self):并且所有变量访问都应该在print_student函数中使用self self.name等。

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()

答案 1 :(得分:0)

第1行:def__init__(self, name='', school='', grade=''):

  

def__init__之间没有空格

     
    

添加空格以修复语法错误。

  

同时

Python 2使用raw_input()
Python 3使用input()

  
    

https://hub.docker.com/_/mysql/