Home > Software design >  How do I query a certain list element in python after they meet some conditions using a loop?
How do I query a certain list element in python after they meet some conditions using a loop?

Time:06-11

I am trying to go through a list (which is set as the parameter in a function) to query the suburb taken as an input from the user. The query is then searched for in the list and if a match is found, the total sales from the suburb's stores are added and the average store sales for that suburb is calculated.

here is the list:

Hm001,6,Frankton,42305.67_
Hm002,10,Glenview,21922.22_
Hm003,7,Silverdale,63277.9_
Hm004,13,Glenview,83290.09_
Hm005,21,Queenwood,81301.82_
Hm006,14,Hillcrest,62333.3_
Hm007,7,Frankton,28998.8_
Hm008,19,Chartwell,51083.5_
Hm009,6,Glenview,62155.72_
Hm0010,8,Enderley,33075.1_
Hm0011,10,Fairfield,61824.7_
Hm0012,15,Rototuna,21804.8-
Hm0013,11,Fairfield,62804.7_

if follows the format: ID, Num of employees, suburb, and sale volume.

I have written the function below but I don't know what is wrong with the function.

def query_suburb_stats(records):
    suburb = input("Enter a suburb name: ")
    print(suburb)
    sales = 0
    avg_sales  =  0
    for match in records:
      if suburb.lower() == match[2].lower():
       sales  = match[3]
       avg_sales = avg_sales/sales
     
    if suburb.lower() != records[2].lower():
      print(f"No matching name for {suburb}")
    else:
      print(f"The total sale volume for the stores in {suburb} is: {sales}")
      print(f"The average sales for {suburb} is: {avg_sales}")

CodePudding user response:

Your code will work with the following changes:

def query_suburb_stats(records):
    suburb = input("Enter a suburb name: ")
    print(suburb)
    matches = 0
    sales = 0
    avg_sales  =  0
    for match in records:
        if suburb.lower() == match[2].lower():
            matches  = 1
            sales  = float(match[3])
     
    if not matches:
        print(f"No matching name for {suburb}")
    else:
        avg_sales = sales/matches
        print(f"The total sale volume for the stores in {suburb} is: {sales}")
        print(f"The average sales for {suburb} is: {avg_sales}")

With Glenveiw as input, it will output:

The total sale volume for the stores in Glenview is: 167368.03
The average sales for Glenview is: 55789.34333333333
  • Related