协助固定While循环

时间:2018-11-12 23:05:58

标签: python while-loop pycharm

以下是我要执行的操作:

  1. 提示用户“您想添加学生吗?”
  2. 如果用户输入“是”,则会提示他们“您要添加谁?”
  3. 添加学生姓名后,将再次提示“您是否要添加学生?”,直到用户输入“否”为止。
  4. 如果用户输入“否”,我要打印用户输入的所有学生。

据我所知,我尝试在下面进行编码:

students = []


initial_input = 'Yes'
second_input = ''

while initial_input == 'Yes':
    initial_input = input('Do you want to add a student? ')
    if initial_input == 'Yes':
        second_input = input('Who do you want to add? ')

        if initial_input == 'No':
            students.append(second_input)

print(students)

运行时,它不会打印出我在下面输入的名称:

Do you want to add a user? Yes
Who do you want to add? John
Do you want to add a user? Yes
Who do you want to add? Tim
Do you want to add a user? No
[]

Process finished with exit code 0

有人可以请我解释我在做什么错吗?

1 个答案:

答案 0 :(得分:1)

这是一个简单的展示位置问题。只有在学生对添加学生的回答为“否”的情况下,您才添加学生。试试这个:

while initial_input == 'Yes':
    initial_input = input('Do you want to add a student? ')
    if initial_input == 'Yes':
        second_input = input('Who do you want to add? ')
        students.append(second_input)

print(students)