🎉 恭喜! 🎉
你出色地完成了任务!这是一个不小的挑战,但你找到了正确答案。你离编程大师又近了一步!继续保持,每一步都让你更强大。
你好!我是我们班的班长。在学年结束时,我需要从同学们那里收集所有教科书并送到图书馆。按照规定,每位学生必须上交恰好10本教科书。
我需要一个能帮助我记录的程序。程序首先需要询问今天有多少位学生会来交书。然后,它需要依次询问每位学生带来了多少本教科书。
在学生输入他上交的教科书数量后,程序必须立即给出反馈:
同时,程序需要统计所有已收集教科书的总数。当所有学生的询问完成后,程序必须输出最终收集到的书本总数。
第一行:班级中的学生人数(一个整数)。
后续行:每个学生上交的课本数量(一个整数)。每个数字在循环内从新的一行输入。
在循环过程中:向每位学生发送关于其教材交付状态的消息(一行)。
循环结束后:发送包含已收集教材总数量的最终消息(一行)。
3
10
8
11
干得好,所有教科书都已到位!
你还没有通过所有教科书。缺少:2
你多交了额外的教科书!多余:1
教科书总数:29
forcycleThe 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).
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
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
break and continueSometimes you don't have to go through the whole cycle to the end. There are special operators for this.
break operatorThe 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.
continue operatorThe 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.
break and continue is in a nutshellbreak: "Stop, car!". Stops the cycle completely.continue: "This one doesn't fit, let's do the next one!". Skips only the current step.else block in the forThe 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
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.
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.
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.
# Запрашиваем общее количество учеников, которые будут сдавать учебники
total_students = int(input())
# Создаем переменную для хранения общего количества собранных учебников, начальное значение - 0
total_books = 0
# Устанавливаем норму учебников на одного ученика
required_books = 10
# Запускаем цикл, который повторится для каждого ученика
for i in range(total_students):
# Запрашиваем количество учебников у текущего ученика
student_books = int(input())
# Добавляем сданные книги к общему счетчику
total_books = total_books + student_books
# Проверяем, соответствует ли количество сданных книг норме
if student_books == required_books:
# Если ученик сдал ровно 10 книг
print("Молодец, все учебники на месте!")
elif student_books < required_books:
# Если ученик сдал меньше 10 книг
print(f"Ты сдал не все учебники. Не хватает: {required_books - student_books}")
else:
# Если ученик сдал больше 10 книг
print(f"Ты сдал лишние учебники! Лишних: {student_books - required_books}")
# После того как все ученики сдадут учебники, выводим итоговое количество
print(f"\nВсего собрано учебников: {total_books}")
🎉 恭喜! 🎉
你出色地完成了任务!这是一个不小的挑战,但你找到了正确答案。你离编程大师又近了一步!继续保持,每一步都让你更强大。
AD
广告
正在运行代码...