Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Aprenda A Declaração else em um Loop while | O Loop While
Tutorial de Loops em Python

book
A Declaração else em um Loop while

Em Python, o bloco else pode ser adicionado a um loop while. O bloco else é executado quando o loop termina normalmente, ou seja, quando a condição do loop se torna False sem encontrar uma instrução break.

O bloco else é executado quando a condição do loop se torna False, significando que o loop completou todas as iterações.

travel_list = ['Monako', 'Luxemburg', 'Liverpool', 'Barcelona', 'Munchen']

# Initialize index
i = 0

# Iterate through the destinations
while i < len(travel_list):
print(travel_list[i])
i += 1
else:
print('All destinations have been listed!')
1234567891011
travel_list = ['Monako', 'Luxemburg', 'Liverpool', 'Barcelona', 'Munchen'] # Initialize index i = 0 # Iterate through the destinations while i < len(travel_list): print(travel_list[i]) i += 1 else: print('All destinations have been listed!')
copy

Neste exemplo, o loop while itera por cada destino na travel_list e o imprime. Uma vez que todos os destinos são listados, a condição i < len(travel_list) se torna False, acionando o bloco else, que confirma a conclusão.

Se o loop terminar com uma instrução break (por exemplo, quando uma cidade específica é encontrada), o bloco else não é executado.

# List of travel destinations
travel_list = ['Monako', 'Luxemburg', 'Liverpool', 'Barcelona', 'Munchen']

# Initialize index
i = 0

# Search for a specific destination
while i < len(travel_list):
if travel_list[i] == 'Barcelona':
break
print(travel_list[i])
i += 1
else: # This won't execute if break is triggered.
print('All destinations have been listed!')
1234567891011121314
# List of travel destinations travel_list = ['Monako', 'Luxemburg', 'Liverpool', 'Barcelona', 'Munchen'] # Initialize index i = 0 # Search for a specific destination while i < len(travel_list): if travel_list[i] == 'Barcelona': break print(travel_list[i]) i += 1 else: # This won't execute if break is triggered. print('All destinations have been listed!')
copy

Aqui, o loop para assim que encontra 'Barcelona'. O bloco else é ignorado porque o loop não termina normalmente, mas é interrompido pela instrução break.

question mark

Qual das seguintes afirmações sobre o bloco else em um loop while em Python está correta?

Select the correct answer

Tudo estava claro?

Como podemos melhorá-lo?

Obrigado pelo seu feedback!

Seção 2. Capítulo 5

Pergunte à IA

expand
ChatGPT

Pergunte o que quiser ou experimente uma das perguntas sugeridas para iniciar nosso bate-papo

some-alt