• 1
    数据输入输出
    • 任务
  • 2
    条件语句
    • 任务
  • 3
    for循环
    • 任务
  • 4
    字符串
    • 任务
  • 5
    while循环
    • 任务
  • 6
    列表
    • 任务
  • 7
    二维数组
    • 任务
  • 8
    字典
    • 任务
  • 9
    集合
    • 任务
  • 10
    函数与递归
    • 任务
  • к

课程 3. FOR cycle

难度:

任务«评估分析»

💻 Python

想象一下,你是一名成功的自由职业者。为了保持你的高声誉,你决定编写一个小型辅助程序。该程序将分析客户以100分制给你留下的评分。你的任务是——及时追踪所有低于50分的评分,以便联系不满意的客户,找出低评分的原因并改进你的工作。

任务:
编写一个程序,首先请求输入待分析的总评论数。然后,在循环中请求输入每条评论的评分。如果评分低于50分,程序应立即在屏幕上显示一条警告消息。如果检查完所有评论后,没有发现任何低评分,程序必须显示最终消息,表明所有评论均为正面评价。

输入格式

第一行:评论总数(一个整数,& nbsp; integer )。
后续行:客户评价(整数,& nbsp; integer ),每行一个,数量与第一行所示一致。

输出格式

如果评估分数低于50:显示一条警告消息(字符串,string)。每个低评分可以对应多条此类消息。
如果没有发现低评分:显示一条最终消息,表示所有评价均为正面(字符串,string)。

示例

输入

5
95
49
100
30
80

输出

注意!发现低分:49
注意!发现低分:30

提示

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
测试 1
测试 2
测试 3
测试 4
测试 5
测试 6
测试 7
测试 8
测试 9
测试 10
开发者解答
# Запрашиваем у пользователя общее количество отзывов для проверки
# и преобразуем введенную строку в целое число (integer)
total_reviews = int(input())

# Создаем "флаг" для отслеживания, была ли найдена хотя бы одна низкая оценка.
# Изначально считаем, что низких оценок нет (False).
low_score_found = False

# Запускаем цикл, который повторится столько раз, сколько отзывов мы указали.
# Переменная i будет меняться от 0 до total_reviews - 1, но мы ее не используем.
for i in range(total_reviews):
    # Внутри цикла считываем оценку очередного клиента и преобразуем ее в число.
    score = int(input())
    
    # Проверяем условие: является ли полученная оценка строго меньше 50.
    if score < 50:
        # Если условие истинно, выводим предупреждающее сообщение с указанием балла.
        print(f"Внимание! Обнаружен низкий балл: {score}")
        # Меняем значение флага на True, так как мы нашли низкую оценку.
        low_score_found = True

# После того как цикл завершил работу и все оценки проверены,
# мы проверяем значение нашего флага.
if not low_score_found: # "if not low_score_found" эквивалентно "if low_score_found == False"
    # Если флаг остался False, значит низких оценок за все время работы цикла не было.
    # Выводим сообщение, что все в порядке.
    print("Все отзывы положительные!")

🎉 恭喜! 🎉

你出色地完成了任务!这是一个不小的挑战,但你找到了正确答案。你离编程大师又近了一步!继续保持,每一步都让你更强大。

AD

广告

red-snake blue-snake green-snake

正在运行代码...

AI助手

你好!我是你的编程助手。随时向我提问关于 Python 的问题——我可以解释函数、方法,并帮助你完成当前任务!