修复 if 循环中的“列表索引超出范围”?

扎眼的阳光 python 235

原文标题Fix ‘List Index out of Range’ in if loop?

试图制作一个测试三个类的测试程序(学生和教师是 Person 的子类),我在教授的帮助下完成了大部分工作。缺点是,我的代码允许我很好地编写学生信息,但是当我尝试为教师信息运行它时,它默认返回学生信息。我已经尝试调整和#ing 出学生提示的位置,但它给了我“列表索引超出范围”的错误。如果有人可以查看代码并查看我哪里出错了,那就太好了。

#import student, instructor, and person


from Student2 import Student
from Instructor2 import Instructor
from person import Person

#create function for asking what type of person we're inputting
def what_type_of_person():
    
    #while we're not done
    not_done = True
    while not_done:
        #ask what type of person, if student or instructor
        #get first letter of response and put it in uppercase
        type_of_person = input('Are you entering (S)tudents or (I)nstructors? ')[0].upper()

        #if the input is either S or I
        if type_of_person in ('S', 'I'):

            #we're not done and move on
            not_done = False

        #Otherwise raise error
        else:
            print('Invalid input. Please try again.')

    #return type_of_person
    return type_of_person


#create function of finding out how many people we're getting
def get_how_many(title):

    #not done is considered true right now, which means we aren't done getting people to get info from
    not_done = True
    
    #so while we're not done, we make a try/except program
    while not_done:

        #trying to
        try:
            #get a quanity of 'how many people are we getting info from?'
            qty = int(input(title))

            #if they input less than 0, we're done and don't need to do anything
            if qty > 0:
                not_done = False

            #otherwise, if they do input <1, display the error
            else:
                print('You must have at least 1 data point to enter. Please try again.')

        #otherwise, print an exception
        except:
            print('Invalid input! Please try again.')

    #return the quantity of people
    return qty

        
#create function for asking questions, passing in what_type
def create_prompts(what_type):

    #ask for the first, middle, last name dob
    prompts = ['First name: ', 'Middle name: ', 'Last name: ', 'Date of birth (mm/dd/yyyy): ']

    #if what_type is I
    if what_type == 'I':

        #add prompts for instructor
        prompts.append('Salary: ')
        prompts.append('Degree (PhD or MS): ')
        prompts.append('Department (CIS, CNG, CSC): ')

    #otherwise add prompts for student
    if what_type == 'S':
        prompts.append('Major: ')
        prompts.append('GPA: ')
        prompts.append('Class year (FR, SO, JR, SR): ')

    #return prompts
    return prompts

#create function for loading list, pass in what_type and how_many
def load_list(what_type, how_many):

    #make the create_prompts function labelled as 'prompts'
    prompts = create_prompts(what_type)

    #empty list
    list_of_people = []

    #for each person they want to get info from
    for i in range(how_many):
        try:
            #make an empty list called answers
            answers = []
            #for every prompt in prompts
            for prompt in prompts:
                #append the answers in prompt to the answers list
                answers.append(input(prompt))

            #if the type of person is an instructor
            if what_type == 'I':
                #create a variable containing all answers 1-7 from instructor
                to_append = Instructor(answers[0], answers[1], answers[2], answers[3], answers[4], answers[5], answers[6])

            #otherwise create a variable containing all answers 1-7 from student
            else:
                to_append = Student(answers[0], answers[1], answers[2], answers[3], answers[4], answers[5], answers[6])

            #append this variable to the list of people list
            list_of_people.append(to_append)

        #if none of that works, create an exception
        except Exception as e:
            print(e)
            print("You must re-enter this individual's information. Refresh and try again")

    #return the list of people
    return list_of_people

#create function for printing people, pass in what_type and load_list
def print_people(what_type, load_list):

    #if the type of person is an instructor
    if what_type == 'I':
        #print following instructor statement
        print('Instructor list is: ')

    #otherwise print student statement
    else:
        print('Student list is: ')

    #for each person in the list
    for person in load_list:
        #print their information
        print(f'{person}\n')



def  main():

    #pass what type of person and label it as person type
    #(because python doesn't like multiple variables of the same name
    person_type = what_type_of_person()
    
    #creating the question to ask how many people
    how_many = get_how_many('How many people do you want to create? ')

    #get the load list, passing on what_type_of_person and how_many
    #and label it as list_of_people
    list_of_people = load_list(what_type_of_person, how_many)

    #pass on that list and the person_type to the print function
    print_people(person_type, list_of_people)
    


if __name__ == '__main__':
    main()

我已经进行了一些挖掘,并且围绕“创建提示”功能似乎出了问题。我尝试移动一些东西并移除其他东西,但似乎没有任何效果。如果您需要我拥有的 3 类 python 程序,请告诉我。什么都有帮助!

原文链接:https://stackoverflow.com//questions/71686169/fix-list-index-out-of-range-in-if-loop

回复

我来回复
  • little_birdie的头像
    little_birdie 评论

    我看到了一些问题,但最大的问题就在这里:

    if type_of_person == 'S' or 'I':
    

    这行代码用英文表示“如果==左侧的变量type_of_person==右侧的变量具有相同的值,则执行下面的缩进代码。

    现在,右边是什么?你有:

    'S' or 'I'
    

    这在英文中的意思是“如果'S'评估为Trueor'I'评估为True,则表达式的值为True

    由于任何长度非零的字符串在评估为布尔值时始终评估为True,因此您==的右侧始终是True的值..它不是有问题的字母,因此它永远不会匹配type_of_person

    你想要的是:

    if type_of_person in ('I', 'S'):
    

    要么

    if type_of_person == 'I' or type_of_person == 'S':
    

    这些比较将字符串与字符串进行比较,这是您想要做的。

    2年前 0条评论