Requiring 2 while statments to be true

Viewed 46
import string
import re

r = re.compile(r'[a-zA-Z]+')
name = input("Enter your name: ")

while not r.match(name):
    print("Name must be in letters!")
    name = input("Enter your name: ")

while len(name) > 12 or len(name) < 3:
    print("Name must be between 3 and 12 letters!")
    name = input("Enter your name: ")

print("Welcome,",name+".")

This works fine, but if I enter a name that fulfills the first requirement, but not the second and then enter a number, which length is between 3 and 12 characters, it accepts it. For example: first input is xx, then the message: "Name must be between 3 and 12 letters!", second input 1111, which is accepted with: "Welcome, 1111."

3 Answers

You can condense them into one while loop, so that you can check both conditions at once:

import string
import re

r = re.compile(r'[a-zA-Z]+')
name = input("Enter your name: ")

while not r.match(name) or len(name) < 3 or 12 < len(name):
    if not r.match(name):
        print("Name must be in letters!")
    if len(name) < 3 or 12 < len(name):
        print("Name must be between 3 and 12 letters!")
    name = input("Enter your name: ")

print("Welcome,", name+".")

Check for both conditions in the while loop, and print a message based on which condition it is:

while not r.match(name) or len(name) > 12 or len(name) < 3:
    if len(name) > 12 or len(name) < 3:
        print("Name must be between 3 and 12 letters!")
    
    if not r.match(name):
        print("Name must be in letters!")
    name = input("Enter your name: ")

If you're using a version of python that has the walrus operator, you can avoid the second calculation of the conditions:

while (letters := not r.match(name)) or (length := (len(name) > 12 or len(name) < 3)):
    if length:
        print("Name must be between 3 and 12 letters!")
    
    if letters:
        print("Name must be in letters!")
    name = input("Enter your name: ")

Note that you can skip the regex because str.isalpha() does the same thing.

The easiest way to do this would be to write a function, to separate the messages from the loop condition:


def is_valid(name):
    # You don't need a regular expression for this!
    if not name.isalpha():
        print("Name must be in letters!")
        return False
    if len(name) > 12 or len(name) < 3:
        print("Name must be between 3 and 12 letters!")
        return False
    # No issues, so name is valid
    return True

name = input("Enter your name: ")

while not is_valid(name):
    name = input("Enter your name: ")

print("Welcome,", name + ".")
Related