ComeçarComece de graça

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.

Este exercício faz parte do curso

Python for R Users

Ver curso

Instruções do exercício

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

Exercício interativo prático

Experimente este exercício completando este código de exemplo.

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')
Editar e executar o código