我需要在Python中使用 while循环 * 编写代码来执行以下操作:
1.要求用户输入班级所有学生的姓名。
1.用户应能够键入*“停止”以指示所有学生的姓名已输入。
1.打印出退出循环后用户输入的名称总数。**
以下是我到目前为止的代码:
print ("""Enter the names of all the pupils in your class.
Type 'Stop' to indicate that all the names have been entered.""")
count_names = {}
while True:
pupil_names = input("Enter a name: ")
# I know there is code missing here, but I can not figure out what it must be
# I have 'count_names' as my counter variable
if pupil_names == "Stop":
print(f"There are {count_names} students")
break
我到处寻找帮助,但什么也找不到。
最接近的答案/帮助:
count number of names in list in python
Counting the input in a while loop?
4条答案
按热度按时间u0njafvf1#
请尝试以下代码
ruarlubt2#
通过将
count_names
设置为{}
,您将其设置为 * dictionary *,这不符合您的目的。您可以将所有名称保存到 * list *([]
)中,或者只将名称的数量保存为数字(以0
开始)。此外,我将
print
语句放在while-block之外,因为您的任务需要它。它将运行完全相同。gk7wooem3#
将count_names更改为:
并添加以下一行:
这个应该能用
7vhp5slm4#
我希望这对你有帮助,因为这是我对这个问题的看法: