简体   繁体   中英

while loop won't break, python

Soo i have this problem that the while loop just wont break:

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')

i get output:

Enter your chosen email below!
Try again
Did you mean eq@gmail.com

i expected:

Enter your chosen email below!
Try again

Thank you for your time!

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

Try using in instead of the for loop:

if ' ' in email:
    break

When you break in the for loop, you are only breaking that loop, not the while loop.

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

"The break statement, like in C, breaks out of the smallest enclosing for or while loop."

You are breaking out of the for loop, not the while loop. I think this does what you want:

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')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM