简体   繁体   中英

Python infinite while loop issue

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?

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.

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}')

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.

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.

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()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM