Get startedGet started for free

Loops

Loops are used when there are multiple elements that need to undergo the same series of calculations or same blocks of code. Typically, items are placed in a list and we write a for loop such that the same block of code is executed across each element in the list.

The key here is that we are not copy-pasting code multiple times to perform this repeated action.

Given a list of integers, you can write a for loop to print each integer in the list. Note, just like conditional statements, indentation matters.

int_list = [1, 2, 3, 4]

for value in int_list:
    print(value)

1
2
3
4

This exercise will build on the previous example, but instead of a single value to test our binge drinking status, you will have a list of values.

This exercise is part of the course

Python for R Users

View Course

Exercise instructions

Write a for loop that loops over the list of num_drinks, and prints whether or not the person is a binge drinker.

Hands-on interactive exercise

Have a go at this exercise by completing this sample code.

num_drinks = [5, 4, 3, 3, 3, 5, 6, 10]

# Write a for loop
____ ____ ____ num_drinks:
    # if/else statement
    if drink <= 4:
        print('non-binge')
    else:
        print('binge')
Edit and Run Code