Skip to content

script_20.py - Email Validator Basic

Code

Python
#!/usr/bin/env python3
"""Email validator basic"""

email = input("Enter email address: ")

if "@" in email and "." in email:
    at_index = email.index("@")
    dot_index = email.rindex(".")
    if at_index < dot_index and at_index > 0 and dot_index < len(email) - 1:
        print("Email format appears valid")
    else:
        print("Email format invalid")
else:
    print("Email must contain @ and .")

Explanation

Line 4: email = input("Enter email address: ") - email is string type - No conversion - emails are text

Line 6: if "@" in email and "." in email: - Two in membership checks - Both must be True for and to succeed - Checks for presence of @ symbol and dot character - Basic validation - ensures minimum required characters

Line 7: at_index = email.index("@") - .index() is string method that returns integer position - Returns the index of FIRST occurrence of "@" - Indexes start at 0 (first character is position 0) - Raises ValueError if "@" not found (but we already checked with in) - at_index stores integer position

Line 8: dot_index = email.rindex(".") - .rindex() is like .index() but searches from the right (reverse) - Returns position of LAST occurrence of "." - Useful for domains like "name@example.co.uk" (finds last dot) - dot_index stores integer position

Line 9: if at_index < dot_index and at_index > 0 and dot_index < len(email) - 1: - Complex boolean with multiple conditions (all must be True) - at_index < dot_index: @ must come before the last dot - at_index > 0: @ cannot be first character (needs username) - len(email) returns total string length (integer) - len(email) - 1 is index of last character - dot_index < len(email) - 1: dot cannot be last character (needs TLD) - Validates structure: [username]@[domain].[tld]