0

I am trying to make a script that asks for user input in Python, it is supposed to error with the response "Please enter first name", and then return the user back to the initial input question prompt.

This isn't working, instead after asking for both the first and last name if no name is given for both I am thrown into an infinite loop of the first error.


# User input for first name
first_name = input('Enter FIRST name here: ')
# User input for last name
last_name = input('Enter LAST name here: ')

def print_name():

    # store user input in separate variable
    fname = first_name
    lname= last_name

    while True:
        # throw error if user enters no first name
        if len(fname) == 0:
            # error msg
            print('No FIRST name entered...')
            # loop back to prompt asking for first name
            continue
        else:
            # if first name given move on to prompting for last name
            # break loop
            break

    # loop into prompting user for last name
    while True:
        # throw error if user enters no last name
        if len(lname) == 0:
            print('No LAST name entered...')
            # loop back to prompt asking for last name
            continue
        else:
            # if last name given move on to running print command
            # break loop
            break

        return fname, lname

    print(f'your name is {fname} {lname}')

print_name()

Please can someone help me understand whats going wrong here? It should only loop back to asking for a first name (or last name) when nothing is given, other wise it should print the users name to console. both names should be given too, if first name is not given then id expect an error in the first while loop, like wise if last name is not given.

Also is there a better way to do this? using 2 while loops seems wrong?

3
  • You enter an infinite loop because len(fname) never changes. You need to ask for input again, this time storing it as fname. Commented May 4, 2020 at 11:39
  • How about you write a function that will loop until it gets a nonempty string from the user, and then returns it? Then you can call it twice to get the two names. Commented May 4, 2020 at 11:39
  • What should I do when someone answers my question Commented May 4, 2020 at 11:50

5 Answers 5

3

Don't repeat yourself. If you copy and paste a section of code, stop and think. It should either be a function, or a loop.

def wait_for_input(prompt):
    data = ""
    while data == "":
        data = input(prompt).strip()
    return data


def print_name(fname, lname):
    print(f'your name is {fname} {lname}')


first_name = wait_for_input('Enter FIRST name: ')
last_name = wait_for_input('Enter LAST name: ')

print_name(first_name, last_name)

Also, don't use comments to repeat what the code says.

Sign up to request clarification or add additional context in comments.

1 Comment

This is something like what I was trying before using different functions to do different things but it got way more messy for me and I gave up haha. Yes you solution works a treat, it doesn't spit an error back to the user but this is actually better as they cant move forward until giving something. Perfect Thank you, and I understand it :)
2

The issue is with your infinite loops, you can simplify your function like:

def print_name():
    first_name = ""
    last_name = ""
    # User input for first name
    while first_name == "":
        first_name = input('Enter FIRST name here: ')
    # User input for last name
    while last_name == "":
        last_name = input('Enter LAST name here: ')
    print(f'your name is {first_name} {last_name}')

Comments

1

I have the impression you are new at this:

While-loops generally look as follows:

while <condition>
...
<check_condition>
...

This means that in most cases, at every time the loop is executed, the condition is re-calculated and checked again by the while.

In your case, this would become something like:

while (len(fname) == 0)
<show_error_message>
<get fname again>

The case you have written here (while true) also exists and is used regularly, but in very different cases, like in multi-threaded event-based programs:

while true
<get_event>

This means that a part of the program (a so-called thread) is waiting for an event (like a buttonclick) to be catched and then something happens. This, however, is mostly done in multi-threaded applications, which means that the "main" program is doing something, while a subprogram is handling the events, which are coming in.

1 Comment

I am sort of new to it yes. thank you for this its good to know.
1

I am not fully understanding why you need so many loops. Something like this should do:

def print_name():
    fname = input('Enter FIRST name here: ')
    if len(fname) == 0:
        raise Exception('No FIRST name entered...')

    lname= input('Enter LAST name here: ')
    if len(lname) == 0:
        raise Exception('No LAST name entered...')

    print(f"your name is {fname} {lname}")

And if all you wanted is to repeat this loop all you need to do is nest your print_name() function in a loop.

EDIT: Now that I seen other answers, I believe @Tomalak answer is better, was not getting what you really wanted.

3 Comments

I am not an expert, I know there is a better way to do this and not have so many loops I just didn't know how I was trying to maintain DRY code but ended up with more issues so gave up. i was not aware of the "raise Exception" part of code. Thank you
This also works but does not loop the user back to the initial question on exception it just ends the script, this is why I thought a while loop would be included.
Yes, that is why I think Tomalak's answer is better, I did not take re-asking the user for the information into account.
0

Try this code:

def print_name():

    # store user input in separate variable
    first_name = input('Enter FIRST name here: ')

    fname = first_name



    while True:
        fname = first_name


        # throw error if user enters no first name
        if len(fname) == 0:
            # error msg
            print('No FIRST name entered...')
            first_name = input('Enter FIRST name here: ') 
            # loop back to prompt asking for first name
            continue
        else:
            # if first name given move on to prompting for last name
            # break loop
            break

    # loop into prompting user for last name
    while True:
        last_name = input('Enter LAST name here: ')
        lname= last_name

        # throw error if user enters no last name
        if len(lname) == 0:
            print('No LAST name entered...')
            # loop back to prompt asking for last name
            continue
        else:
            # if last name given move on to running print command
            # break loop
            break

        return fname, lname

    print(f'your name is {fname} {lname}')

print_name()

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.