首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何在python中使用break来结束while循环?

如何在python中使用break来结束while循环?
EN

Stack Overflow用户
提问于 2021-05-09 11:03:34
回答 2查看 65关注 0票数 1

我在这里写了一个循环,询问用户是否想重复一段指令。并想给用户三次尝试来选择他想要的(是/否),如果他没有结束循环。这是我的代码:

代码语言:javascript
运行
复制
# Ask for repeating
i = 0
def question():
    global i
    while True:
        print("Give another try?")
        answer = input("(Y/N): ")
        answer = answer.upper()
        if answer == 'Y':
            main()
        elif answer == 'N':
            print("Thank you for participating")
            break # here it works when 'n' is typed
        else: # i count how much the while loop id repeated
            if (i < 2):
                i += 1
                question()
            else: # else is executed when i == 2
                print("don't Play with us!!")
                break # here it doesn't work.

我需要帮助。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2021-05-09 11:11:27

代码语言:javascript
运行
复制
x = True
i = 0
def question():
    # Ask for repeating
    global i
    global x
    while x is True:
        print("Give another try?")
        answer ='a'
        answer = answer.upper()
        if answer == 'Y':
            pass
        elif answer == 'N':
            print("Thank you for participating")
            break  # here it works when 'n' is typed
        else:  # i count how much the while loop id repeated
            if (i < 2):
                i += 1
                question()
            else:  # else is executed when i == 2
                print("don't Play with us!!")
                x = False  # here it doesn't work.
票数 1
EN

Stack Overflow用户

发布于 2021-05-09 11:19:38

在最后一个else块之外添加另一个分隔符。你的代码应该是

代码语言:javascript
运行
复制
i = 0
def question():
    global i
    while True:
        print("Give another try?")
        answer = input("(Y/N): ")
        answer = answer.upper()
        if answer == 'Y':
            main()
        elif answer == 'N':
            print("Thank you for participating")
            break # here it works when 'n' is typed
        else: # i count how much the while loop id repeated
            if (i < 2):
                i += 1
                question()
            else: # else is executed when i == 2
                print("don't Play with us!!")
                break # here it doesn't work.
            break
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/67453942

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档