Search code examples
pythonif-statementuser-input

How to repeat the function when there is no user input


My program is supposed to store contacts. When I enter the number I need the program to keep asking for the number if there is no user input. For now my program considers the contact added even if there is no number entered by user input.

I tried to use a while True or if not. The closest I got to solving the problem was when the program asked a second time for to enter a number but that's all.

def add_contact(name_to_phone):

    # Name...
    names = input("Enter the name of a new contact:")


    # Number...
    numbers = input("Enter the new contact's phone number:")


    # Store info + confirmation
    name_to_phone[names]= numbers
    print ("New contact correctly added")

    return
Select an option [add, query, list, exit]:add
Enter the name of a new contact:Bob
Enter the new contact's phone number:
New contact correctly added
Select an option [add, query, list, exit]:

As I said the program should keep asking for a number if there is no user input and go to the next step only when there is a user input.


Solution

  • Use a loop.

    def add_contact(name_to_phone):
        while True:
           name = input("Enter the name of a new contact: ")
           if name:
               break
    
        while True:
            number = input("Enter the new contact's phone number: ")
            if number:
                break
    
        name_to_phone[name] = number
        print("New contact correctly added")
    

    You may want to do a more thorough check for the name and number beyond checking if the input is empty or not.

    In Python 3.8 or later, you can simply each loop a bit. Maybe this will become an standard idiom; maybe not.

    while not (name := input("Enter the name...: ")):
        pass