为了账号安全,请及时绑定邮箱和手机立即绑定

有没有办法简化Python中的“While循环”/“For循环”交互?

有没有办法简化Python中的“While循环”/“For循环”交互?

开心每一天1111 2023-12-12 15:43:41
  for a in list:        answer_or_help = False        print(a.question)        while answer_or_help not in ("q", "a"):                answer_or_help = input("Press a for Answer, h for Help, q to quit: ")                if answer_or_help == "h":                        print(a.hint)                elif answer_or_help == "a":                        print(a.answer)                elif answer_or_help != "q":                        print("This is not a valid answer")        else:                if answer_or_help == "q":                        break当我输入“q”时,我试图退出 FOR 循环,但我不确定这是最好的方法。我将不胜感激任何帮助。谢谢你!!
查看完整描述

3 回答

?
梦里花落0921

TA贡献1772条经验 获得超5个赞

假设每个对象有一个问题。你不需要一个while. input()函数将无限期地等待用户输入。


idx = 0

while idx < len(your_list):

    

    obj = your_list[idx]

    

    print(obj.question)

    answer_or_help = input("Press a for Answer, h for Help, q to quit: ")

    

    if answer_or_help == 'q':

        break

    

    elif answer_or_help == "h":

        print(obj.hint)

        

    elif answer_or_help == "a":

         print(obj.answer)

         idx += 1 # moving object


    else:

        print("This is not a valid answer")


查看完整回答
反对 回复 2023-12-12
?
阿波罗的战车

TA贡献1862条经验 获得超6个赞

您可以使用break、continue和pass语句执行这些操作。 Break 语句 在 Python 中,break 语句为您提供了在触发外部条件时退出循环的机会。您可以将 Break 语句放在循环语句下的代码块中,通常放在条件 if 语句之后。


 number = 0


for number in range(10):

    if number == 5:

        break    # break here


    print('Number is ' + str(number))


print('Out of loop')

continue 语句 continue 语句使您可以选择跳过触发外部条件的循环部分,但继续完成循环的其余部分。也就是说,循环的当前迭代将被打乱,但程序将返回到循环的顶部。


continue 语句将位于循环语句下的代码块内,通常位于条件 if 语句之后。


number = 0


for number in range(10):

    if number == 5:

        continue    # continue here


    print('Number is ' + str(number))


print('Out of loop')

Pass 语句 当触发外部条件时,pass 语句允许您处理该条件,而不会以任何方式影响循环;除非发生中断或其他语句,否则所有代码将继续被读取。


与其他语句一样,pass 语句将位于循环语句下的代码块内,通常位于条件 if 语句之后。


  number = 0


for number in range(10):

    if number == 5:

        pass    # pass here


    print('Number is ' + str(number))


print('Out of loop')


查看完整回答
反对 回复 2023-12-12
?
幕布斯7119047

TA贡献1794条经验 获得超8个赞

我将它包装在一个函数中,这样你就可以从它返回。


def show_questions(questions):

    for item in questions:

        print(item.question)

        while True:

            user_input = input("Press a for Answer, h for Help, q to quit: ")

            if user_input == 'h':

                print(item.hint)

            elif user_input == 'a':

                print(item.answer)

                break

            elif user_input == 'q':

                return

            else:

                print("This is not a valid answer)

a请注意如何清楚地看到 Answer和h这种方式之间的区别q:h让您处于内部循环中,a中断内部循环并q通过从函数返回来中断两个循环。


查看完整回答
反对 回复 2023-12-12
  • 3 回答
  • 0 关注
  • 82 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信