在Python中,计算用户输入的“while循环”中的名称总数

8fsztsew  于 2023-05-19  发布在  Python
关注(0)|答案(4)|浏览(92)

我需要在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?

u0njafvf

u0njafvf1#

请尝试以下代码

print ("""Enter the names of all the pupils in your class.
Type 'Stop' to indicate that all the names have been entered.""")

count_names = 0 # Initialize count_names to 0

while True:
    pupil_names = input("Enter a name: ")
    
    if pupil_names == "Stop":
            print(f"There are {count_names} students")
            break

    count_names += 1 # Add 1 each time we count a pupil
ruarlubt

ruarlubt2#

通过将count_names设置为{},您将其设置为 * dictionary *,这不符合您的目的。您可以将所有名称保存到 * list *([])中,或者只将名称的数量保存为数字(以0开始)。

names_list = [] # version 1
names_count = 0 # version 2

while True:
    new_name = input("Enter a name: ")

    if new_name == "Stop":        
        break

    names_list.append(new_name) # version 1
    names_count += 1            # version 2

print(f"There are {len(names_list)} students") # version 1
print(f"There are {names_count} students")     # version 2

此外,我将print语句放在while-block之外,因为您的任务需要它。它将运行完全相同。

gk7wooem

gk7wooem3#

将count_names更改为:

count_names = 0

并添加以下一行:

while True:
  pupil_names = input("Enter a name: ")
  count_names += 1

这个应该能用

7vhp5slm

7vhp5slm4#

我希望这对你有帮助,因为这是我对这个问题的看法:

print('''Enter the names of all the pupils in 
the class. Enter "Stop" once all the names have 
been entered.
''')

pupil_count = 0

while pupil_count >= 0:
   pupil_names = input("Enter a name: ")

   pupil_count += 1

   if pupil_names == "Stop":

       print(f"\nThe total number of pupils in the class is: {pupil_count - 1}")

       break

相关问题