for loops

if statements allow conditionally execute 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 can use for loops with any iterable like range():
for index in range(5):
	print(f'Input the next number {index}:')
	n = int(input())
	print(f'Great! you\'ve entered {n}')
User Input:


7


9


-4


8


0
Program output:

Input the next number 0:
Great! you've entered 7

Input the next number 1:
Great! you've entered 9

Input the next number 2:
Great! you've entered -4

Input the next number 3:
Great! you've entered 8

Input the next number 4:
Great! you've entered 0
So, the syntax of the for loop includes a list or an iterable (like range()) and for each element in that list, the block of code inside the for will be executed. The value of the following the for keyword takes the values of the list one by one.
In the first example, the month variable first took the value December, then the print statement was executed, then the month variable took the value January, then the print statement was executed again, then the same happened for February and March.
In the second example, the index variable first took the value 0, then the block of code inside the for-statement was executed, then the index took the value 1, then 2, 3, and finally 4.

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'
]
 

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