If I run this program
emails=[]
a=(0)
while a==(0):
user_email= input("Please write email")
if "#" in user_email:
if ".edu"in user_email:
print("Adding email to list")
emails.append(user_email)
print(emails)
else:
a=(0)
a=(0)
else:
print("Error:Email does not meet requirements")
a=(0)
And I type an input that meets only one of the requirements, it only displays the error message in one scenario. How could I make the error message show up in both cases where the requirements are not met since I cant write two conditions in the "if" statement.
Use and keywords, print error message for all other scenarios.
if '#' in user_email and '.edu' in user_email:
pass
else:
print('error')
Or
if all(keyword in user_email for keyword in ['#', '.edu']):
pass
else:
print('error')
emails=[]
while True:
user_email= input("Please write email: ")
if user_email.count("#") == 1 and user_email.count(".edu") == 1:
print("Adding email to list")
emails.append(user_email)
print(emails)
else:
print("Error:Email does not meet requirements")
Or using regular expression:
import re
emails=[]
while True:
user_email= input("Please write email: ")
email_pt = re.compile("^[\w.]+#[\w.]+\.edu$")
if email_pt.search(user_email):
print("Adding email to list")
emails.append(user_email)
print(emails)
else:
print("Error:Email does not meet requirements")
Here is a simple function for you to use that can replace your nested if statements:
#A nice function that returns true if # and .edu are in the mail
def matches(user_email):
boolean = True
if '#' not in user_email:
boolean = False
if '.edu' not in user_email:
boolean = False
return boolean
#Your new code
emails=[]
a=(0)
while a==(0):
user_email= str(input("Please write email: "))
#New function in use
if matches(user_email):
print("Adding email to list")
emails.append(user_email)
print(emails)
else:
print("Error:Email does not meet requirements")
Hope this helps! :D
Related
what i want is if the user enter the email address in a wrong format, it should trigger the except, print the error and head back to try.
x = True
while x==True:
try:
email = (input("Enter Email: "))
if re.fullmatch(regex,email):
x = False
except:
print("Email is inValid. Please type in this format: email#email.com")
the code works fine if you correctly input the email, but when you do it wrong, it will head back to try without triggering the except
Your code does not raise any exception. Just use a good old "if/else" statement instead, as follows:
x = True
while x==True:
email = (input("Enter Email: "))
if re.fullmatch(regex,email):
x = False
else:
print("Email is inValid. Please type in this format: email#email.com")
And it could be a little shorter, as follows:
while True:
email = input("Enter Email: ")
if re.fullmatch(regex, email):
break
print("Email is inValid. Please type in this format: email#email.com")
You can use the assert statement if you prefer the flow of raising and catching an exception:
while True:
try:
email = input("Enter Email: ")
assert re.fullmatch(regex, email)
break
except AssertionError:
print("Email is inValid. Please type in this format: email#email.com")
I am making a login page in which I have to cover all the login test scenarios. I am am validating all type of input the user is putting, but the problem is when a while condition handles one test condition, that same while condition is not repeated after the another while condition runs. if the same test condition occurs again after user puts the same input value after another type of input value. Here is my code:
import re
userDetails=[]
accountDetails= {"FirstName": "Ajay", "LastName": "Kumar","DateOfBirth":"24-07-1992","Account Number":"4242342345234","Balance Currency":"Rs","Balance Amount":"5000"}
specialCharacters = re.compile('[#_!#$%^&*()<>?/\|}{~:]')
firstName=str(input("Enter First Name"))
while True:
if firstName=="":
print("Name cannot be blank")
firstName=str(input("Enter First Name"))
while True:
if firstName.isdigit():
print("Name cannot be in digits")
firstName=str(input("Enter First Name"))
while True:
if specialCharacters.search(firstName) != None:
print("Please don't enter special characters")
firstName=str(input("Enter First Name"))
while True:
if firstName!=accountDetails.get("FirstName"):
print("The account does not exist with the given details, please try again")
print("Enter valid first name")
firstName=str(input("Enter First Name"))
else:
userDetails.append(firstName)
Use exceptions and functions and do all your validation at once:
class ValidationError(Exception):
pass
def validate_name(name):
name = name.strip()
if not name:
raise ValidationError("Name cannot be blank")
if name.isdigit():
raise ValidationErrir("Name cannot be in digits")
if specialCharacters.search(name) is not None:
raise ValidationError("Please don't enter special characters")
if name != accountDetails.get("FirstName"):
raise ValidationError("The account does not exist with the given details, please try again")
def get_first_name():
while True:
first_name = input("Enter First Name")
try:
validate_name(firstName)
except ValidationError as e:
print(str(e))
else:
# ok we're good
return first_name
first_name = get_first_name()
do_something_with(first_name)
One way to write it:
import re
specialCharacters = re.compile('[#_!#$%^&*()<>?/\|}{~:]')
accountDetails= {"FirstName": "Ajay", "LastName": "Kumar","DateOfBirth":"24-07-1992","Account Number":"4242342345234","Balance Currency":"Rs","Balance Amount":"5000"}
not_valid = True
while not_valid:
firstName=str(input("Enter First Name: "))
if firstName == "" or specialCharacters.search(firstName) != None or firstName.isdigit() or firstName!=accountDetails.get("FirstName"):
not_valid = True
continue
else:
not_valid = False
It could also be done with a break.
I suggest refactoring the validation to a separate function, something like this.
import re
userDetails = []
accountDetails = {
"FirstName": "Ajay",
"LastName": "Kumar",
"DateOfBirth": "24-07-1992",
"Account Number": "4242342345234",
"Balance Currency":"Rs",
"Balance Amount":"5000",
}
specialCharacters = re.compile('[#_!#$%^&*()<>?/\|}{~:]')
def validate(accountDetails, firstName):
if not firstName:
return "Name cannot be blank"
if firstName.isdigit():
return "Name cannot be in digits"
if specialCharacters.search(firstName):
return "Please don't enter special characters"
if firstName != accountDetails.get("FirstName"):
return "The account does not exist with the given details, please try again"
return None # No error
while True:
firstName = str(input("Enter First Name"))
error = validate(accountDetails, firstName)
if error:
print(error)
else:
break
userDetails.append(firstName)
You need to understand how while works, or loops in general. Let's go through your code -
firstName=str(input("Enter First Name"))
# We got an input
while True: # (Oh, I have to run indefinitely)
....
The first while True will get you stuck in an infinite loop and the code won't be executed ever after. Rather than doing this, do something like -
while not len(firstName): # (Okay, I will run till I get a non empty firstname)
# your code
# and subsequent conditions
while not firstName.isdigit():
# your code
#.... and so on
Or better rather, put these conditions in a function
this is my password checker code (whether it is valid or not)
I need to run the password checker for 5 times, until it's valid.
If it's valid, I have to break out of the loop.
The password should be more than 7 characters.
The password needs to include both numbers (at least two) and characters.
(If not, return False)
There should be no space.
If there is anything else than numbers and characters, I need to return False
I need to run my password_checker function in the for loop,
but I'm not so sure what to say after 'if'.
I have tried -
if a=False:
print(password_checker(i))
print(Invalid password)
but it didn't work.
Also, I don't understand how should I call my password_checker() in the for loop.
Finally, I need to put a break in my for loop
if the password in the input is valid.
But I'm not sure where is the appropriate part to place it
def password_checker(password):
a=True
num_Count = 0
if password.isalpha() == True:
print ("error! needs numbers")
a = False
if password.isnum() == True:
print ("error! needs characters")
a = False
if password.isspace() == True:
print ("error! no space allowed")
a = False
if len(password)<=8:
print ("error! needs more than 8 characters")
a = False
for i in range(0, 10):
num_Count += password.count(i)
if num_Count(password.count()) < 2:
print("error! needs at least 2 numbers")
a = False
password = str(input("Enter password: "))
for i in range(0,5):
if ____________________:
print(password_checker(i))
print("Invalid password")
else:
print(password_checker(i))
print("Valid password")
break
How should I correct my code in order to make my function work?
for i in range(0,5):
password = str(input("Enter password: "))
password_checker_result = password_checker(password)
if not password_checker_result:
print("Invalid password")
else:
print("Valid password")
break
This code will work for you, now let me explain:
The flow is as following:
This is done 5 times (is inside the for loop):
1) Request password from user.
2) Check if password is valid.
3) Print according to valid/not valid result.
The fact that you are using a for loop does not require you to actually use the iteration index (meaning 'i' in our case)
I have tried to create an app in Python that makes a user create a password and then makes them verify it. Obviously I had to create a loop so that when the user entered an unmatching password they had to try again. I am not very experienced with loops so here is what I got. How do I make this work?
here is the code:
password = raw_input ("Create a password: ")
passwordv = raw_input ("Retype your password: ")
a = ("Passwords don't match! Please try again!: ")
b = ("Congrats, you have created a password")
def password():
if password == passwordv :
print ("Congrats, you have created a password")
else :
print (a)
return password
return passwordv
while password !=passwordv:
print (a)
here is another set of code trying to do the same thing:
password = raw_input('Create a password: ')
passwordv = raw_input('Veryify your password: ')
while (password != passwordv):
print raw_input('Passwords do not match, try again: ')
if (password == passwordv) :
print ('Password set')
break
Your conditional to test whether the passwords match was included in the loop which checks that they don't match -- so, it never gets run.
Try this instead:
password = raw_input('Create a password: ')
passwordv = raw_input('Verify your password: ')
while (password != passwordv):
print raw_input('Passwords do not match, try again. ')
password = raw_input('Create a password: ')
passwordv = raw_input('Verify your password: ')
continue
print ('Password set')
Note how only the code that should be run if the passwords don't match is included within the while loop.
What you need here is an "N and a half times loop". To avoid repeating code (guided by the DRY principle) you might consider writing a function to get the passwords. The following might work:
def get_passwords():
password = raw_input('Create a password: ')
passwordv = raw_input('Veryify your password: ')
return password, passwordv
pw1, pw2 = get_passwords()
while pw1 != pw2:
print "Sorry, passwords do not match"
pw1, pw2 = get_passwords()
The loop won't be entered at all if the original passwords match. Otherwise it will repeat until they do.
password=raw_input('Enter password: \t\t\t')
passwordv=raw_input('Enter password again to verify: \t')
if password == passwordv:
print "\ncongratz you have created password"
else:
print "\nPlease try again...!"
while password != passwordv:
password=raw_input("Enter password: \t\t\t")
passwordv=raw_input("Enter password again to verify: \t")
if password == passwordv:
print"\ncongratz you have created password"
else:
print"\nPlease try again...!"
I know this one is long, It is just for basic understanding
The other answers provide the code that will do what you want. I thought that it could be interesting to tell you a little bit more what was wrong with the code you provided because the problem is more about your understanding of how things work.
1st attempt: a variable and a function have the same name
# Here you define your password variable as a string
password = raw_input ("Create a password: ")
[...]
# And then you reassign it here: it contains now the address of that function!
def password():
[...]
# Now you're comparing a function to a string: they'll never be equal
while password !=passwordv:
[...]
This could have been avoided simply by changing the name of your function (which is never called by the way so I'm not sure what you wanted to do but I thought you might find that interesting). Further reading: Python: function and variable with same name
2nd attempt: the values of the variables stay the same
password = raw_input('Create a password: ')
passwordv = raw_input('Veryify your password: ')
# At this point, if the test is true, you'll reach the end of the code without
# displaying the 'Password set' message you wanted
while (password != passwordv):
# This only prints a message
print raw_input('Passwords do not match, try again: ')
# The condition below can never be true: you just tested that they were
# different but did nothing to give them new values!
if (password == passwordv) :
print ('Password set')
break
The way to fix that is what the other answers provide: take your message out of the loop (getting out of the loop means that your condition was met) ; make sure that you do something inside the loop that will assure that the next test will be different from the previous one (otherwise, you will end up testing the same values over and over again) ; to avoid breaking inside the loop, set your values outside the loop, and then get new values inside the loop in case the initial test failed.
Here's an idea:
First define these:
MinPass = 6
MaxPass = 12
Then this:
print ("Now, lets try with a password. Please enter one here")
EnteredPassword = input("Password: ")
while len(EnteredPassword) < MinPass:
print ("That password is too small. Please try again")
EnteredPassword = input("Password: ")
while len(EnteredPassword) > MaxPass:
print ("That password is too long, please try again")
EnteredPassword = input("Password: ")
Hope this helps!
I cant get my code to return back to asking the user for their email.
I have tried several things, but cant figure it out. Right now it continues on to the next function.
how can i get my code to return to asking for user email until its set to true?
def name_email(name):
correct_email = False
email = str(input('what is your email: '))
print()
try:
while correct_email == False:
if '#' in email:
print('name and email accepted \n')
print('name: ',name)
print('email: ',email)
print()
correct_email = True
else:
print('email invalid, please try again \n')
return
except:
raise ValueError
If you're using Python 2.x use raw_input() instead of input() because input() tries to evaluate whatever you enter.
I think you're using Python 3.x though because of the prints with parentheses. So keep using input()
You don't even need to do the if else condition, you can just put it in the while condition.
def name_email(name):
correct_email = False
email = str(input('what is your email: '))
print()
try:
while '#' not in email:
print('email invalid, please try again \n')
email = str(input('what is your email: '))
#why return if you want it to ask them again?
#return
except:
raise ValueError
print('name and email accepted \n')
print('name: ',name)
print('email: ',email)
print()
That stray return inside your else statement is what's causing your problem. Try removing it.
You can try this code :
def name_email(name):
correct_email = False
while correct_email == False:
email = input('what is your email: ')
if '#' in email:
print('name and email accepted \n')
print('name: ',name)
print('email: ',email)
correct_email = True
else:
print('email invalid, please try again \n')
return email