9.2 - Valid email
Problem
Write a procedure that will check if an email contains an @ symbol.
Example run 1
Enter email: super@studyparty.com Email valid
Example run 2
Enter email: super@studyparty.com Email valid
| 1 | Check if email is valid | IN | |
| OUT |
1.1 set valid to false
1.2 for i from 0 to length of email – 1
1.3 if email substring[i : i+1] = “@” then
1.4 valid = true
1.5 if valid is true then
1.6 display “Valid email”
1.7 else
1.8 display “Invalid email”
1.9 end if
# Main
email = input("Enter email: ")
check_valid_email(email)
def check_valid_email(email):
valid = False
for i in range(len(email)):
if email[i:i+1] == "@":
valid = True
if valid == True:
print("Valid email")
else:
print("Invalid email")
# Main
email = input("Enter email: ")
check_valid_email(email)
"""
Procedure: check_valid_email(email)
-----------------------------------
This procedure takes an email string as a parameter.
It checks the string one character at a time using a loop.
The line:
if email[i:i+1] == "@":
means:
- Look at the substring starting at position i and ending at i+1.
- This gives exactly one character from the string.
- Compare that single character to "@".
If "@" is found anywhere in the string, we mark the email as valid.
Finally, the procedure prints either "Valid email" or "Invalid email".
"""
def check_valid_email(email):
valid = False # assume it is not valid to start with
# loop through each position in the string
for i in range(len(email)):
# Take one character at position i
# Compare it to "@"
if email[i:i+1] == "@":
valid = True
# After the loop, check the result
if valid == True:
print("Valid email")
else:
print("Invalid email")
"""
Main program
------------
1. Ask the user to enter an email address.
2. Call the procedure check_valid_email(email)
and pass the user input as the parameter.
"""
# Main
email = input("Enter email: ")
check_valid_email(email)
Extension
Update the procedure so that it checks that the email has an @ and .
username@location.com
- @
- .
Enter email: super@studypartycom Email invalid Enter email: super@studyparty.com Email valid