python 检查用户输入的电子邮件密码循环

python check user input for email password loop

我想让我的脚本在继续脚本的其余部分之前验证电子邮件密码是否正确。我确定这只是一个简单的循环,但我想不出一个简单的方法来做到这一点。现在我的脚本是:

import arcpy, os, sys, time, subprocess, collections, datetime, smtplib
from datetime import datetime
print("This script will check your email password to verify it is  correct.")
usr = "your_email@gmail.com"
print("Please enter the password for " + usr + ":")
psw = raw_input()


def passwordcheck(usr,psw):
    server=smtplib.SMTP('smtp.gmail.com:587')
    server.starttls()
    server.login(usr,psw)
    server.quit()
    print("Thank you. Password was correct.")


try:
    passwordcheck(usr,psw)

except:
    print("Password was incorrect.")

我想要一个简单的循环,允许用户 3 次尝试输入正确的密码,然后如果没有输入正确的密码,则终止脚本。

这会更有意义。

def passwordcheck(usr,psw):
    server=smtplib.SMTP('smtp.gmail.com:587')
    server.starttls()
    try:
        server.login(usr,psw)
        ret = True
    except:
        ret = False
    server.quit()
    return ret

for i in range(3):
    psw = raw_input("Please enter the password for " + usr + ": ")
    if passwordcheck(usr,psw) is False:
        print("Password was incorrect.")
    else:
        print("Thank you. Password was correct.")
        break

因为在接近错误源的地方处理错误并采取相应行动应该(是?)被认为是最佳实践。 此外,考虑到您将 Password was incorrect 保留在函数调用之外,您可能也应该保持正输出接近(始终保持相似的输出彼此接近)。

所以处理passwordcheck中的错误,改为处理return函数的代码
这可能不是 SO 的典型问题,因为您的初始代码没有任何问题,因为更多的代码审查会想到它。

应该这样做:

def passwordcheck(usr)
    print("This script will check your email password to verify it is  correct.")
    usr = "your_email@gmail.com"
    for i in range(3):
        print("Please enter the password for " + usr + ":")
        psw = raw_input()
        try:
            server=smtplib.SMTP('smtp.gmail.com:587')
            server.starttls()
            server.login(usr,psw)
            server.quit()
            print "Thank you. Password was correct."
            break
        except:
            if i < 3:
                print "Password was incorrect. Try again:"
                continue
        print "Password was incorrect. 3 times"
        break