如何结束while循环并跳过for循环?

2024-09-29 23:27:28 发布

您现在位置:Python中文网/ 问答频道 /正文

如果用户输入‘no’,程序也不会经过for循环,我该怎么做呢。我不想这样tmpfile.write(行)如果用户输入“no”。在

def remove():
    coname = raw_input('What company do you want to remove? ') # company name
    f = open('codilist.txt')
    tmpfile = open('codilist.tmp', 'w')
    for line in f:
        if coname.upper() in line:
            while True:
                answer = raw_input('Are you sure you want to remove ' + line.upper() + '?')
                if answer == 'yes':
                    print line.upper() + '...has been removed.'               
                elif answer == 'no':
                    break  # HERE IS WHERE I NEED HELP
                else:
                    print 'Please choose yes or no.'                   
        else:
            tmpfile.write(line)
    else:
        print 'Company name is not listed.'
    f.close()
    tmpfile.close()
    os.rename('codilist.tmp', 'codilist.txt')

Tags: no用户answeryouforrawlineupper
3条回答

设置一个标志变量,然后退出while循环。然后在for循环中,检查是否设置了标志,然后断开。在

注:if是一个循环

Python有一些异常,可以用它来代替GOTO类型的构造。在

class Breakout(Exception):
    pass

def remove():
    coname = raw_input('What company do you want to remove? ') # company name
    f = open('codilist.txt')
    tmpfile = open('codilist.tmp', 'w')
    try:
        for line in f:
            if coname.upper() in line:
                while True:
                    answer = raw_input('Are you sure you want to remove ' + line.upper() + '?')
                    if answer == 'yes':
                        print line.upper() + '...has been removed.'
                    elif answer == 'no':
                        raise Breakout()
                    else:
                        print 'Please choose yes or no.'
            else:
                tmpfile.write(line)
        else:
            print 'Company name is not listed.'
    except Breakout:
        pass

    f.close()
    tmpfile.close()
    os.rename('codilist.tmp', 'codilist.txt')

请注意,在中间出现了异常。在

最简单的方法是创建一个获取用户输入的函数:

def get_yes_or_no(message):
    while True:
        user_in = raw_input(message).lower()
        if user_in in ("yes", "no"):
            return user_in

并按如下方式修改原始函数:

^{pr2}$

相关问题 更多 >

    热门问题