Reputation: 1
def getUsername():
username = raw_input("Enter Your Username: ")
if not username[0].isalpha():
print "wrong"
getUsername()
else:
return username
am trying to check if the first char of the string username is a alphabetical char and if it's not to ask the user for hes user name again and if it is set it to username.
but when i run though the function more the once i get back the value None from username what i mean by that is when i run the function and give it a bad value once it works fine and asks me again for a value but when i print out the value i get back a None.
can you please tell me why.
and of course how to fix it thanks in the advance :
Upvotes: -1
Views: 48
Reputation: 52929
You're missing a return
in your recursive call to getUsername()
:
def getUsername():
username = raw_input("Enter Your Username: ")
if not username[0].isalpha():
print "wrong"
return getUsername()
else:
return username
Without it your function recursively calls getUsername()
, exits the if/else block and falls off from the function, which implicitly returns None
.
From the data model documentation:
None
This type has a single value. There is a single object with this value. This object is accessed through the built-in name None. It is used to signify the absence of a value in many situations, e.g., it is returned from functions that don’t explicitly return anything. Its truth value is false.
The return statement returns with a value from a function.
return
without an expression argument returns None. Falling off the end of a function also returns None.
Upvotes: 2
Reputation: 12542
Why even use a recursive Function for this just use a while Loop.
def getUname():
while True:
username = raw_input("name:");
if not username[0].isalpha():
print "wrong";
else:
return username;
it should return the same.
Upvotes: 0