2

I am having trouble with this block of code. I just started programming in Python 2.7 and I would like to have some help.

Here is the code:

username=raw_input("Please give me a username")
def gebruikersnaam():
    username(len)

    if len(username) >= 8:
        print "Well done"
    elif len(username) <= 1:
        print "More characters please" #Please try again, input your username again.

The username must consist of a number too. And I would like to have the user input the username again if the number of characters is 0. Thanks!

Mike Müller
  • 82,630
  • 20
  • 166
  • 161
  • 3
    Possible duplicate of [Asking the user for input until they give a valid response](http://stackoverflow.com/questions/23294658/asking-the-user-for-input-until-they-give-a-valid-response) – vaultah Jan 17 '16 at 09:41
  • 1
    What kind of errors are you seeing? What do you think they mean? What ways have you attempted to resolve these issues? – ktbiz Jan 17 '16 at 10:14

2 Answers2

2

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())
Mike Müller
  • 82,630
  • 20
  • 166
  • 161
  • Thanks, but the code I must use a def statement. I cant figure it out. – Alexander Vos Jan 17 '16 at 11:05
  • Thanks alot, you solved my problem. Very easy to read code. Allthough I dont understand the line "if not any(c in username for c in '0123456789'):" – Alexander Vos Jan 17 '16 at 11:24
  • Great that it helped. BTW, you can [accept](http://stackoverflow.com/help/accepted-answer) an answer if it solves your problem. I will add some more explanation about the line with `any`. – Mike Müller Jan 17 '16 at 11:30
  • Ok thanks, How would I do that. I cant accept the answer, I dont see a button for it. Where is it located. Btw, I tried your code again. But If I put a a character , say for instance a4, or c4. These print functions would not work: print("More characters please.") print("Please try again, input your username again.") – Alexander Vos Jan 17 '16 at 11:35
  • Did you add `from __future__ import print_function` as the first line in your file? – Mike Müller Jan 17 '16 at 11:39
  • `len('c4')` is 2. You need to change your code: `elif len(username) <= 2:` if you want to catch this. – Mike Müller Jan 17 '16 at 11:41
0

You can try something like this:

import re

def check(name):
    if bool(re.search(r'\d', name)) and name != '' and len(name) > 4:
        return 1
    else:
        return 0

while True:
    username = raw_input("Please give me a username=>")
    if check(username) == 1:
        print "Username ok"
        break
    else:
         print "Username needs at least 1 digit or too short. Try again"

I've managed to cover the case of the space and the username containing at least one digit. I've used regular expressions. Hope that helps somehow!

Best Regards

incalite
  • 3,077
  • 3
  • 26
  • 32