im trying to learn python and wrote this code to check if the user input is a name (containing only of letters and a "space" However if I try to run it and an error occurs, it keeps on telling me "Please enter a valid name" and then asks me to "Please enter your name" but never stops How do I break the second if loop I tried setting valid = true at different places but i cant figure out how to break the loop once its activated
This is my code:
def get_name():
name = input("Please enter your name: ")
valid = True
for x in name:
if not x.isalpha() or x == "":
valid = False
if valid == False:
print("Please enter a valid name.")
get_name
else:
return name
else:
return name
name_checked = get_name()
print(name_checked)
Thanks for any help :)
CodePudding user response:
Situations like this call for a while True construct. Something like this:
def get_name():
while True:
if (name := input('Enter a name: ')).isalpha():
return name
print('Invalid name')
print(get_name())
Or, if you like (almost) one-liners then:
def get_name():
while not (name := input('Enter a name: ')).isalpha():
print('Invalid name')
return name
print(get_name())
CodePudding user response:
First of all, x will never be equal to ""
so that check is pointless. Second, you need to return the result of a recursive calls. Not only will it let you actually do something with the result, but it will also break you out of the loop as return stops execution of function call. get_name
-> return get_name()
CodePudding user response:
Instead of recursively calling get_name (recursion is not what you want for this example), repeat your line name = input("Please enter your name: ")
to get a new name.
In addition to that, check again the following code:
valid = False
if valid == False:
print("Please enter a valid name.")
get_name
else:
return name
How do you expect, could the else
-branch ever be executed?
CodePudding user response:
Move name validity check to another function - this makes the code more readeble imho.
def invalid_name(name):
for x in name:
if not x.isalpha():
return True
return False
def get_name():
name = input("Please enter your name: ")
while invalid_name(name):
name = input("Please enter a valid name: ")
return name
name_checked = get_name()
print(name_checked)
CodePudding user response:
def get_name():
name = input("Please enter your name: ")
valid = True
for x in name:
if not x.isalpha() or x == "":
valid = False
break
if not valid:
print("Please enter a valid name.")
get_name()
else:
return name
name_checked = get_name()
print(name_checked)