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")
Related
i am trying to validate every input value but stuck here where if user put wrong value then my function stop taking other input & ask him to correct the error.
import re
import os.path
from csv import DictWriter
service ={}
class App:
def __init__(self):
pass
def services(self):
Problem is here
name=input("Enter Name: ")
name_r = re.match('^[a-zA-Z]{3,20}$',name)
if name_r:
print("true")
else:
print("Wrong Value Entered. Please Enter Correct Name")
i wanna use try & except block but exactly don't know how to use in this case.
if i put validated value in except block then rest of the input will also have have their own except block (am confused guide me) also the main problem, is there any short way to do this because if i validate each line like this so it will take so much time.
phone=input("Enter PTCL: ")
email=input("Enter Email: ")
mobile=input("Enter Mobile: ")
address=input("Enter Address: ")
service_type=input("Enter Problem Type: ")
date_time=input("Enter Date & Time: ")
msg=input("Enter Message: ")
Below Code is fine
#getting input values
service['name'] = name_r
service['ptcl'] = phone
service['mobile'] = mobile
service['date_time'] = date_time
service['service_type'] = service_type
service['address'] = address
service['msg'] = msg
service['email'] = email
file_exists = os.path.isfile(r"sevices.csv")
with open(r"sevices.csv",'a',newline='') as for_write:
writing_data = DictWriter(for_write,delimiter=',',fieldnames=["Name","Email","PTCL","Mobile","Service Type","Date & Time","Address","Message"])
if not file_exists:
writing_data.writeheader()
writing_data.writerow({
'Name': service['name'],
'Email':service['email'],
'PTCL':service['ptcl'],
'Mobile':service['mobile'],
'Service Type':service['service_type'],
'Date & Time':service['date_time'],
'Address':service['address'],
'Message':service['msg']
})
o1= App()
o1.services()
The easiest way to accomplish what you want is to create a while loop that exits on an accepted input.
while True:
name=input("Enter Name: ")
name_r = re.match('^[a-zA-Z]{3,20}$',name)
if name_r:
break
else:
print("Wrong Value Entered. Please Enter Correct Name")
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
accounts = {"key":"value","thy":"l23","user2":"psw2"}
a = input("Enter username: ")
b = input("Enter password: ")
if accounts[a:b] == True:
print("Welcome")
TypeError: unhashable type: 'slice'
What does the error mean? How can I fix it?
If I understand what you're trying to do (validate a username and password), you need to go about it this way:
accounts = {"key":"value","thy":"l23","user2":"psw2"}
a = input("Enter username: ")
b = input("Enter password: ")
if accounts[a] and accounts[a] == b:
print("Welcome")
This tests to see if a password exists for the entered user, then tests to see if the entered password matches the one stored in accounts.
The major problem with this method is that the entered password is printed out when you type it in. To get around this, use the getpass.getpass() function.
The
if accounts[a:b] == True:
should read
if accounts.get(a) == b:
The reason I used accounts.get(a) instead of accounts[a] is that the former would return None if a does not contain a valid username (the latter would raise an exception).
Can you tell me the input so that the check statement is passed along with the try..except of the input pin
#!/usr/bin/python
# Secure Pin system
import sys
users = {'admin': '<REDACTED>'}
def register(username, password):
if username in users:
return "User already exits."
users[username] = password
return "Registered Successfully."
def login(username, password):
if username not in users:
return "Wrong pin/password"
if password != users[username]:
return "Wrong pin/password"
if username == "admin":
return "The FLAG is what you entered in the \"Pin\" field to get here!"
return "You must login as admin to get the flag"
def handle_command(command):
if command not in ["REG", "LOGIN"]:
return "Invalid Command!"
print "Username:",
sys.stdout.flush()
username = raw_input()
try:
print "Pin ([0-9]+):",
sys.stdout.flush()
password = input() # we only support numbers in password
except:
return "Please enter a valid password. Pin can only contain digits."
if command == 'REG':
return register(username, password)
if command == 'LOGIN':
return login(username, password)
if __name__=="__main__":
print "Hey welcome to the admin panel"
print "Commands: REG, LOGIN"
try:
print ">",
sys.stdout.flush()
command = raw_input()
print handle_command(command)
sys.stdout.flush()
except:
pass
The code is all right but the only thing is to bypass the input check
There is a bug that is to be identified
If you want to check whether the input from user only has numbers, then you can use the method - str.isnumeric() , to check whether the string only contains numbers.
Example -
>>> "123".isnumeric()
True
>>> "123.21".isnumeric()
False
>>> "abcd".isnumeric()
False
You can do this check instead of a try/except block (since you do not really use the password as a number after this block).
To ensure the user enters a number, you could convert the script to use a function as follows:
def get_input_number(prompt):
while True:
try:
user_num = int(raw_input(prompt))
return user_num
except ValueError:
print "Please enter a valid password. Pin can only contain digits."
password = get_input_number("Pin ([0-9]+): ")
This would then keep prompting until a number is entered.
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