• 1
    Entrada e saída
    • Tarefas
  • 2
    Condições
    • Tarefas
  • 3
    Loop for
    • Tarefas
  • 4
    Strings
    • Tarefas
  • 5
    Loop while
    • Tarefas
  • 6
    Listas
    • Tarefas
  • 7
    Matrizes 2D
    • Tarefas
  • 8
    Dicionários
    • Tarefas
  • 9
    Conjuntos
    • Tarefas
  • 10
    Funções e recursão
    • Tarefas
  • к

Lição 3. FOR cycle

Dificuldade:

Tarefa«Elementos vizinhos»

💻 Python

Um novo scanner de pacotes foi instalado na fábrica. Ele verifica o lote um após o outro. Você & mdash; O programador, que foi instruído a escrever um programa para ele.

O programa primeiro recebe o número de pacotes no lote ( n ). Em seguida, ele começa a receber os códigos inteiros de cada pacote um de cada vez.

O scanner funciona de acordo com as seguintes regras:

  1. Se o código do pacote & mdash; Um número negativo, isso é considerado um erro de digitalização. Tal pacote deve ser ignorado, a mensagem é "Código incorreto, passe." E vá imediatamente para o próximo pacote.
  2. Se o código do pacote for divisível por 13 sem resto (por exemplo, 0, 13, 26, ...), então o pacote é considerado perigoso. É necessário interromper imediatamente toda a verificação, exibir a mensagem "Um pacote perigoso com o código foi encontrado:
    [código]! A verificação foi interrompida." e finalizar o programa.
  3. Se o código do pacote & mdash; Um número comum, não negativo, que não é divisível por 13, então seu valor é adicionado ao valor total de todos os pacotes verificados.
  4. Se todo o lote foi verificado e nenhum pacote perigoso foi encontrado, o programa deve exibir a mensagem "A verificação foi concluída. O valor total dos pacotes:
    [soma]."

Formato de entrada

A primeira linha contém um número inteiro & nbsp; n & nbsp; (1 & le; n & le; 100) & mdash; O número de pacotes na remessa.
As seguintes & nbsp; n linhas contêm um número inteiro & mdash; O código do próximo pacote.

Formato de saída

o programa exibe uma ou mais mensagens dependendo dos códigos dos pacotes:

  • com código negativo:   código incorreto, passe adiante.
  • quando um pacote perigoso é detectado:   um pacote perigoso com código foi encontrado: [code]! A auditoria é interrompida.   (onde
    [code] — é o próprio código).
  • Se a verificação foi concluída com sucesso:   A verificação está concluída. O valor total dos pacotes: [sum].   (onde
    [sum] — é o valor total).

Exemplo

Entrada

5
10
-5
20
15
2

Saída

Código incorreto, aprovado.
A verificação foi concluída. Valor geral das encomendas: 47.

Dica

Basics of the forcycle

The for loop in Python is your main tool for iterating through elements in any sequence. Imagine that you have a box with different items. The for loop allows you to take one item at a time, do something with it, and move on to the next until the items in the box run out.

It is used to iterate over sequences such as lists, strings, tuples, sets, or even keys in a dictionary. The same block of code is executed for each element of the sequence.

Syntax:

for element in sequence:
    # a block of code that will be executed for each element
    # IMPORTANT: this block must be indented!

Here, the element is a temporary variable that is assigned a different value from the sequence at each iteration. You can name this variable any way you want, but it's better to choose a meaningful name (for example, fruit for a list of fruits or letter for a string).

Iterating through the list

A list is an ordered collection of items. The for loop will run through it from the first element to the last.

fruits = ['apple', 'banana', 'cherry']
for fruit in fruit:
    print(fruit)

Conclusion:

apple
banana
cherry

Iterating over the line

A string is, in fact, a sequence of characters. Therefore, the for loop can iterate over it just as easily.

word = "Python"
for a letter in a word:
    print(letter)

Conclusion:

P
y
t
h
o
n

Cycle control: break and continue

Sometimes you don't have to go through the whole cycle to the end. There are special operators for this.

The break operator

The break operator is used to immediately and completely terminate the loop. As soon as the program encounters a break, it immediately exits the loop and continues execution from the next line of code after it.

A useful tip: break is indispensable when you are looking for something. Once you've found what you're looking for, there's no point in continuing the search.

Example: We have a list of numbers, and we want to find the first even number and stop the loop as soon as it is found.

numbers = [1, 3, 5, 6, 7, 9, 10]
for num in numbers:
    if num % 2 == 0: # Check for parity
        print(f"The first even number is found: {num}")
break # Immediately exit the loop
print("The loop is completed.")

Conclusion:

The first even number was found: 6
The cycle is completed.

Please note that the numbers 7, 9, and 10 were not checked, as the cycle was interrupted by the number 6.

The continue operator

The continue operator is used to skip the current iteration and immediately move on to the next one. All the code that is in the loop after continue will not be executed for the current element.

A useful tip: continue is very convenient for "filtering" data inside a loop. If the current item doesn't suit you by some criterion, you just skip it and move on to the next one.

Example: We have a list of numbers, and we want to output all the numbers except the even ones.

numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
for num in numbers:
    if num % 2 == 0: # Check for parity
        continue # If the number is even, skip print() and go to the next number.
    print(num)

Conclusion:

1
3
5
7
9

When num was equal to 2, 4, 6, etc., the if condition was met, continue skipped the print(num) command, and the loop immediately started a new iteration.

The difference between break and continue is in a nutshell

  • break: "Stop, car!". Stops the cycle completely.
  • continue: "This one doesn't fit, let's do the next one!". Skips only the current step.

The else block in the for

loop

The for loop may have an optional else block. This block is executed only if the loop has completed all its iterations naturally, that is, it has not been interrupted by the break operator.

A useful tip: It is a very powerful tool for search tasks. The else block makes it easy to handle a situation where the search has ended but nothing has been found.

Example 1: The loop ended normally

for number in range(3):
print(number)
else:
    print("The cycle is completed without interruptions.")

Conclusion:

0
1
2
The cycle is completed without interruptions.

Example 2: The loop is interrupted by the break

operator
for number in range(3):
if number == 1:
        print("We found 1, we break the loop.")
break
    print(number)
else:
    # This block will not be executed because there was a break
    print("The cycle is completed without interruptions.")

Conclusion:

0
We found 1, we interrupt the cycle.

Practical examples

The sum of all the numbers in the list

This is a classic task for understanding how to work with a cycle and accumulate results.

numbers = [1, 2, 3, 4, 5]
amount = 0 # Initialize the variable to store the amount BEFORE the loop
for a number in numbers:
    sum += number # At each iteration, we add the current number to the total
print(f' Sum: {sum}') # Output the final result AFTER the loop

Conclusion: Amount: 15

A useful tip: Although this method perfectly demonstrates how the loop works, in real code it is better to use the built-in sum() function to find the sum of the list elements: print(sum(numbers)). It's shorter and more efficient.

Finding the maximum number in the list

Here we assume that the first element is the maximum, and then in the loop we compare it with all the others.

numbers = [1, 7, 3, 9, 5]
maximum = numbers[0] # We take the first element as the temporary maximum
for a number in numbers:
    if the number is > maximum: # If we find a number greater than our maximum...
maximum = number # ...then we update the maximum
print(f' Maximum: {maximum}')

Conclusion: Maximum: 9

A useful tip: As with the sum, Python has a built-in function max() for this task: print(max(numbers)). Knowing these functions saves time, but understanding how they work using the for loop is a key skill for a programmer.

main.py
Teste 1
Teste 2
Teste 3
Teste 4
Teste 5
Teste 6
Teste 7
Teste 8
Teste 9
Teste 10
Solução do desenvolvedor
# Сначала считываем количество посылок в партии
num_packages = int(input())

# Инициализируем переменную для хранения общей ценности
total_value = 0

# Запускаем цикл for, который будет выполняться num_packages раз
for _ in range(num_packages):
    # Считываем код очередной посылки
    package_code = int(input())

    # 1. Проверяем на ошибку сканирования (отрицательный код)
    if package_code < 0:
        print("Неверный код, пропуск.")
        # Пропускаем остаток кода и переходим к следующей итерации
        continue

    # 2. Проверяем, не является ли посылка опасной
    if package_code % 13 == 0:
        print(f"Обнаружена опасная посылка с кодом: {package_code}! Проверка остановлена.")
        # Немедленно выходим из цикла
        break

    # 3. Если посылка обычная, добавляем ее ценность к общей сумме
    total_value = total_value + package_code

# 4. Этот блок выполнится, только если цикл for завершился без break
else:
    print(f"Проверка завершена. Общая ценность посылок: {total_value}.")

🎉 Parabéns! 🎉

Você resolveu a tarefa brilhantemente! Foi difícil, mas você encontrou a solução certa. Você está um passo mais perto de dominar a programação! Continue assim.

AD

Publicidade

red-snake blue-snake green-snake

Executando seu código...

Assistente de IA

Olá! Sou seu assistente de programação. Faça qualquer pergunta sobre Python — posso explicar funções, métodos e ajudá-lo com a tarefa atual!