[Python] Having issues with a 'while' loop in Python

Discussão em 'Python' iniciado por Stack, Fevereiro 20, 2025.

  1. Stack

    Stack Membro Participativo

    def first5Star(allOrders):
    position = -1
    index = 0
    month = str(input("Enter month to search"))
    while position ==-1 and index<len(allOrders):
    if allOrders[index].date[3:6] == month[:3] and allOrders[index].rating == 5:
    position = index
    else:
    index += 1
    return position


    Context: allOrders is an array of records, date is in the format Day-Month-Year (eg. 11-Oct-2024) The requirement of the program is to read a txt file into an array of records and find the first person to give a rating of 5 (the part that the function is for). Details of the winning customer are then written into another txt file in the following sub-program:

    def writeDetails(allOrders,position):
    externalFile=open("winningCustomer.txt","w")
    if position >= 0:
    externalFile.write(allOrders[position].orderNum+","+allOrders[position].email+","+allOrders[position].cost)
    else:
    externalFile.write("No winner")
    externalFile.close()


    I have tried implementing elif statements, rewriting the function, doing dry runs with trace tables etc. but nothing has helped. I expect the program to write the details of a customer to a txt file, however no matter what i try it always writes 'No winner' leading me to believe the issue is somewhere in the while loop. It doesn't seem like the if statements conditions are ever met, when they should be, and the position variable is never changed from minus 1

    All help appreciated, and apologies if any formatting or anything isn't ideal, this is my first question :)

    Continue reading...

Compartilhe esta Página