我如何独自结束循环?

时间:2019-04-10 22:37:01

标签: python loops

我正在学习Python。我正在尝试创建一个程序来计算我在大学的最终成绩。我的问题是我是否可以自己结束if循环? 例如。我希望我的程序重复问题“是否要添加分数?” ,只要问题为“是” ,并且答案为< strong>否,我希望程序保留代码的这一部分。

最简单的方法是什么?

noten = [] #list for grades
lp = []    #list for the weight of my different grades
p_antwort = ['y', 'yes'] #p_antwort = positive answer
n_antwort = ['n', 'no']  #n_antwort = negative answer

txt = input("Do you want to add a grade? y/n ")
if txt in p_antwort:
   i = input("What grade did you get? ")
   noten.extend(i)
   txt_2 = input("Do you want to add another one? y/n")
   if txt_2 in p_antwort:
        i = input("What grade did you get? ")
        noten.extend(i)

3 个答案:

答案 0 :(得分:2)

您可以使用带有while变量的done循环,然后在循环的每次迭代中通过检查用户是否有兴趣添加另一个条目来更新done。 / p>

例如:

done = False

while not done:
    # do stuff
    done = input("Want to add another? (y/n)") == "n"

或者您可以使用keep_going变量,基本上执行与上述代码相反的操作。

答案 1 :(得分:1)

您可以使用while循环来保持成绩,直到用户键入退出循环的键(例如quit)为止。

grades = [] 

txt = input("What grade did you get? Enter 'quit' to exit: ")
while txt != 'quit':
    grades.append(txt)
    txt = input("What grade did you get? Enter 'quit' to exit: ")

print(grades)

互动示例

  

您获得了什么年级?输入“退出”退出:A

     

您获得了什么年级?输入“退出”退出:B

     

您获得了什么年级?输入“退出”退出:C

     

您获得了什么年级?输入“退出”退出:D

     

您获得了什么年级?输入“退出”退出:退出

     

['A','B','C','D']

答案 2 :(得分:0)

您可以通过while循环来实现。

首先,您需要为while循环实例化变量文本

text = ""
text = input("Do you want to add a grade? y/n ")
while text != "n":
   if txt in p_antwort:
      # do some stuff
   text = input("Do you want to add a grade? y/n ")

我认为这应该有效