Aan de slagGa gratis aan de slag

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.

Deze oefening maakt deel uit van de cursus

Python for R Users

Cursus bekijken

Oefeninstructies

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

Praktische interactieve oefening

Probeer deze oefening eens door deze voorbeeldcode in te vullen.

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')
Code bewerken en uitvoeren