Basic version
This could be a solution:
from __future__ import print_function
while True:
username = raw_input("Please give me a username: ")
if not any(c in username for c in '0123456789'):
print("Username needs to contain at least one number.")
continue
if len(username) >= 8:
print("Well done")
elif len(username) <= 1:
print("More characters please.")
print("Please try again, input your username again.")
continue
break
Keep asking the user in a while
loop until you get what you want.
This checks if the user name contains at least one digit:
>>> any(c in 'abc' for c in '0123456789')
False
>>> any(c in 'abc1' for c in '0123456789')
True
This part is a so-called generator expression:
>>> (c in 'abc' for c in '0123456789')
<generator object <genexpr> at 0x10aa339e8>
The easiest way to visualize what it is doing, is to convert it into a list:
>>> list((c in 'abc' for c in '0123456789'))
[False, False, False, False, False, False, False, False, False, False]
>>> list((c in 'abc1' for c in '0123456789'))
[False, True, False, False, False, False, False, False, False, False]
It lets c
run through all elements of 0123456789
i.e. it takes on the values 0
, 1
, ... 9
in turn, and checks if this value is contained in abc
.
The built-in any returns True
if any element is true:
Return True
if any element of the iterable is true. If the iterable is empty, return False
.
An alternative way to check for a digit in a string would be to use regular expressions. The module re offers this functionality:
import re
for value in ['abc', 'abc1']:
if re.search(r'\d', value):
print(value, 'contains at least one digit')
else:
print(value, 'contains no digit')
Prints:
abc contains no digit
abc1 contains at least one digit
In a function
You can put this functionality in a function (as requested by the OP in a comment):
def ask_user_name():
while True:
username = raw_input("Please give me a username: ")
if not any(c in username for c in '0123456789'):
print("Username needs to contain at least one number.")
continue
if len(username) >= 8:
print("Well done")
elif len(username) <= 1:
print("More characters please.")
print("Please try again, input your username again.")
continue
break
return username
print(ask_user_name())