for loops

if statements allow conditionally executing blocks of code. In case the condition holds, the program executes those lines, otherwise, it moves on.
for loops allow us to repeat blocks of code. The loop repeats the same actions for each element of the list (iterable - things that allow you to loop over their elements one at a time) passed to it.
for month in ['December', 'January', 'February', 'March']:
    print(month)
This program will print 4 values each one on a separate line as the print is executed for each element in the list (each month):
December
January
February
March
We could achieve the same thing by storing a separate list of months:
months = ['December', 'January', 'February', 'March']
for month in months:
    print(month)
In this example, the month variable first took the value December, then the print statement was executed. After that, the month variable took the value January, then the print statement was executed again, then the same happened for February and March.
 
💡
So, the syntax of the for loop includes a list (or any other iterable), and for each element in that list, the block of code inside the for will be executed. The variable following the for keyword takes the values of the list one by one.
 
Have a look at the interactive section below and try simulating the loop yourself.

Challenge

Given the list of months in a year, write a program that would print the first 5 months in the output. Each month should be printed on a separate line.
months = [
    'January', 'February',
    'March', 'April', 'May',
    'June', 'July', 'August',
    'September', 'October', 'November',
    'December'
]
Tip
You can use the slice operator to extract the first 5 elements of the list
 

Constraints

Time limit: 2 seconds

Memory limit: 512 MB

Output limit: 1 MB

To check your solution you need to sign in
Sign in to continue