'python check user input for email password loop
I would like to have my script verify that an email password is correct before proceeding with the rest of the script. I'm sure it's just a simple loop, but I can't think of an easy way to do it. Right now my script is:
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 = "[email protected]"
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.")
I'd like a simple loop to allow the user 3 attempts at entering the correct password, and then if no correct password was entered, kill the script.
Solution 1:[1]
This would make much more sense.
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
Because handling the error closer to the error source and acting accordingly should (is?) considered best practice.
Also, considering you kept Password was incorrect
outside of the function call you should probably keep the positive output close as well (always keep similar outputs close to each other).
So handle the error in passwordcheck
and deal with the return code of the function istead.
This is probably not a typical question for SO since there's nothing wrong with your initial code there for this is more a code review come to think of it.
Solution 2:[2]
something like this should do it:
def passwordcheck(usr)
print("This script will check your email password to verify it is correct.")
usr = "[email protected]"
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
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 | bmbigbang |