while循环不会破坏,python

时间:2016-03-18 20:43:42

标签: python loops while-loop

所以我有这个问题,while循环不会破坏:

print 'Enter your chosen email below!'
def valid_email(mail):
    email = mail[-len('@gmail.com'):len(mail)]
    failled = mail[0:-len('@gmail.com')]
    condition = True
    while condition:
        for a in mail:
           if a == ' ':
                print 'Try again'
                condition = False

        if email == '@gmail.com':
            print 'You have succesfully logged in our website!'
            break
        else:
            print 'Did you mean ' + failled + 'gmail.com'
        break

print valid_email('eq@gmai l.com')

我得到输出:

Enter your chosen email below!
Try again
Did you mean eq@gmail.com
我预料到:

Enter your chosen email below!
Try again

感谢您的时间!

3 个答案:

答案 0 :(得分:0)

如果您只是想删除空格,那么我建议使用str.replace("","")(其中str =电子邮件地址)

答案 1 :(得分:0)

尝试使用in代替for循环:

if ' ' in email:
    break

当你进入for循环时,你只是打破了那个循环而不是while循环。

答案 2 :(得分:0)

https://docs.python.org/2/tutorial/controlflow.html#break-and-continue-statements-and-else-clauses-on-loops

" break语句与C语句一样,突破了最小的封闭for或while循环。"

你正在打破for循环,而不是while循环。我认为这样做你想要的:

print 'Enter your chosen email below!'
def valid_email(mail):
    email = mail[-len('@gmail.com'):len(mail)]
    failled = mail[0:-len('@gmail.com')]

    if ' ' in mail:
        print 'Try again'

    if email == '@gmail.com':
        print 'You have succesfully logged in our website!'
    else:
        print 'Did you mean ' + failled + 'gmail.com'

print valid_email('eq@gmai l.com')