Reputation: 3
The conditions for the valid emails are
1.It doesn't contain spaces,
2.It contains the @ symbol,
3.After @, there's a dot.
and Note that dots may also occur before @, and in a correct address a dot shouldn't stand immediately after @.
I have tried and written the below code.
def check_email(string):
a = ' ' in string
r = 0
if a != False:
b = "@" in string
if b == True:
c = "@." in string
if c == True:
r = False
else:
r = True
else:
r = False
else:
r = False
return r
a = input("Enter your email :")
print(check_email(a))
Now i am unable to check the error.
the test sample i.e
My e-mail is: [email protected]
Correct output: False
My code output: True
Upvotes: 0
Views: 2032
Reputation: 1
def check_email(string):
return string.find(" ") == -1 and string.find("@") != -1 and string.find("@.") == -1 and string.find(".", string.find("@")) != -1
Upvotes: -1
Reputation: 7
A possible solution using regular expressions:
import re
def email_is_correct(email):
return bool(re.fullmatch("[a-zA-Z0-9.]+@[a-zA-Z0-9]+.[a-zA-Z0-9]+", email)) and True
Upvotes: 0
Reputation: 17387
I would choose a regex based check, but if you want to use just the basic string functions, here are the requested 3 checks (no space; contains @; contains a dot after @, but not immediately after @). It allows nonsense like @@?.
, a regex is really much better.
def check_email(string):
if ' ' in string:
return False
if "@" not in string:
return False
name, domain = string.split('@', 1)
if '.' not in domain[1:]:
return False
return True
Note that a function is not limited to one return at its end. Look how the code becomes readable when a result is returned as soon as possible.
Upvotes: 2
Reputation: 2398
a != False
evaluates to True
if a
is True
and False
if a
is False
. In other words, it evaluates to a
.
With that in mind, the error in your code becomes more obvious: if there is not a space in string
, then a
will be False
, the else
part of your first if
statement will set r = False
and the function returns.
Avoiding comparisons of boolean literals to boolean variables in your if
conditions will make your code much clearer and help spot these kind of problems. It is also entirely unnecessary to do so; if a != False:
for example, is the same thing as if a:
, but it is much clearer what the second one is doing. Similarly, if c == True
is the same as if c:
.
Here is a working version of your code:
def check_email(string):
a = ' ' in string
r = 0
if not a:
b = "@" in string
if b:
c = "@." in string
if c:
r = False
else:
r = True
else:
r = False
else:
r = False
return r
a = input("Enter your email :")
print(check_email(a))
However, it will be better for you in the long run if you consider solutions like using regular expressions, or as suggested in another answer, third-party packages. In particular, it will be hard to meet the 3rd condition in the question in an elegant way using the approach you've used so far.
Upvotes: 0