Search code examples
pythonlistpython-3.xfor-loopnested-loops

Python: nested loops not behaving how I want them to


I need to write a program that calculates the users pay. The part I'm stuck on is where I have to ask for the amount of hours the user worked for each day of the week (which is repeated depending on how many weeks they specified). This is what I have so far:

daysofweek = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]

day = 0
while day < weeks: #user specified variable above 0
  for i in range(len(daysofweek)):
    while True:
      daysofweek[i] = input("Enter the number of hours for week 1 " + daysofweek[i] + ": ")
      try:
        hours = float(daysofweek[i])
        if hours < 0 or hours > 24:
          print("Invalid: Enter a number between 0 and 24")
          continue
        break
      except ValueError:
        print("Invalid: Enter a number between 0 and 24")
day = day + 1

Sorry for the wall of code (some of it is probably irrelevant to my issue). So basically this iterates through the list well the first week but then the day names are replaced with the numbers that are entered. Plus I'm not sure how to store these variables that are entered so I can calculate the pay afterwards. Sorry if this is asking too much, just completely stuck. Thanks!


Solution

  • You could use a dict, associate the day and the number of hour:

    daysofweek = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]
    hours = {}
    for day in daysofweek:
        hour = -1
        while hour < 0 or hour > 24:
            hour = input("Enter the number of hours for week 1 " + day + ": ")
        hours[day] = hour
    

    Then, you can manipulate the day and the associated amount of work:

    from collections import defaultdict
    payperday = defaultdict(lambda: 10, {'Sunday': 20})
    print(sum(payperday[day] * hours[day] for day in daysofweek))
    

    Adding the weeks can be done by adding an integer in dictionnary key, and a loop:

    for week in range(nb_week):
        for day in daysofweek:
            hour = -1
            while hour < 0 or hour > 24:
                hour = input("Enter the number of hours for week " +str(week) + " " + day + ": ")
            hours[week, day] = hour
    

    Then you can ask for the number of hour worked for a particular week & day:

    hours[2, 'Sunday']
    

    Note that some more idiomatic code is enough to get simpler code: usage of for day in daysofweek instead of the C-style for i in range(len(daysofweek)), or usage of dictionnary for association of data, for instance.