0

I have a loop that creates a dictionary based on days of the week stored in a list. The code looks like this:

days_of_theweek = ["Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"]
day_count = 0
index_count = 0
hours = {}   

for i in days_of_theweek:
    if day_count == index_count:
        the_day = days_of_theweek[index_count]
        hours[the_day] = raw_input("  Enter the shift hours for " + str(the_day)+": ")                
        os.system('cls')
        day_count += 1
        index_count += 1
    return hours

The problem is, running this code only returns the first iteration in the loop which is {Monday : some int}. I know this happens because its obviously hitting the return statement after one iteration which stops the loop. Also, i notice removing the return statement allows the loop to run fine but it returns none at the end which is no good lol. My question is how do i run my whole loop and return the completed dictionary.

After_Sunset
  • 674
  • 3
  • 10
  • 25
  • Why are you comparing `day_count` and `index_count`, when they're always equal to each other through the whole program? Also, `i == the_day` here, so `day_count` and `index_count` don't really appear to have any purpose at all. – Mark Whitfield Aug 06 '14 at 18:11

4 Answers4

1

Python is sensitive to the level of indentation. Move the return hours statement out of the for-loop:

def get_hours():
    days_of_theweek = ["Monday", "Tuesday", "Wednesday", "Thursday",
                       "Friday", "Saturday", "Sunday"]
    hours = {}

    for the_day in days_of_theweek:
        prompt = "  Enter the shift hours for {}: ".format(the_day)
        hours[the_day] = int(raw_input(prompt))
        os.system('cls')
    return hours

For other ways to clear the line (thus avoiding the os.system call, see (how to) Print in one line dynamically.)

Community
  • 1
  • 1
unutbu
  • 842,883
  • 184
  • 1,785
  • 1,677
  • @After_Sunset if you found the solution helpfull you should mark it as your chosen answer so that in future people with the similar problem find it easily – Beginner Aug 06 '14 at 18:44
0
for i in days_of_theweek:
    if day_count == index_count:
        the_day = days_of_theweek[index_count]
        hours[the_day] = raw_input("  Enter the shift hours for " + str(the_day)+": ")                
        os.system('cls')
        day_count += 1
        index_count += 1
return hours # return outside the loop
Padraic Cunningham
  • 176,452
  • 29
  • 245
  • 321
0

The return statement is not indented properly. It should be on the same level with the for statement.

Abhinav Kumar
  • 11
  • 2
  • 4
0
weekday = ["Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"]
dayHourDictionary = {}

for day in weekday:
   print "please enter the shift hours for", day ,":"
   shiftHours = input('')
   dayHourDictionary[day]=shiftHours



print dayHourDictionary