Home > Software engineering >  Nested for loop is incorrect for the second number
Nested for loop is incorrect for the second number

Time:04-19

I am testing a simple nested for loop that combines year and month

year_time = range(2014, 2016)
month_time = [
    '0101', '0201', '0301', '0401',
    '0501', '0601', '0701', '0801',
    '0901', '1001', '1101', '1201'
]
for year_time in year_time:
    for month_time in month_time:
        print (str(year_time)   month_time)

The ideal output is 20140101, 20140201 ... 20151101, 20151201. However, the actual output is 20140101, 20140201 ... 20151.

Where do I get wrong?

CodePudding user response:

Your for-loop variable (month_time) is shadowing the list after first iteration of outer loop (after year is changed), so the second iteration of inner loop iterates over string '1201'.
What you need is to change names:

years = range(2014, 2016)
months = ['0101', '0201', '0301', '0401', '0501', '0601', '0701', '0801', '0901', '1001', '1101', '1201']
for year in years:
    for month in months:
        print("".join([str(year), month]))

(I also replaced concatenation with a .join, that's a more pythonic way to join strings, especially if you have more than two of them)

CodePudding user response:

That worked for me, you should try to use 'step', like range(1,10,2) or ,instead, multiple range()...

year_time = range(2014,2016)
year_time_2 = range(2015,2017)

month_time = ['0101', '0201', '0301', '0401', '0501', '0601', '0701', '0801', '0901', '1001', 
              '1101', '1201']

# Range for 2014
for x in year_time:
        for month in month_time:
            print(str(x)   month)
            
# Range for 2015-2016
for n in year_time_2:
    for month in month_time:
        print(str(n)   month)
  • Related