-1

I need to check if the user has entered a value in the Name and Number string and, if not, give them the option to automatically re-enter the value, while avoiding breaking the code due to errors. Also, immediately check whether the name was entered with a capital letter (or automatically replace the first letter with a capital letter).

But I'm stuck at the very beginning because even though the name and number values have been entered, my loop doesn't break and ask for the values again. But I need it to take the user back to the menu after successful input.

Here is my piece of code:

telephone_dict = {"Nino":"0123", "Nick": "0234", "Jake":"0345"}
menu = 1

while menu !=0:
    print("""
1. Add new names and telephone numbers to the dictionary
2. Delete telephone numbers from the dictionary by the given name
3. View the entire telephone dictionary (names and numbers)
4. View/Search for a single entry by name

5. Save Data
6. Load Data

0. Exit
""")
    menu = int(input("Choose menu option: "))

        
    if menu == 1:
        while True:
            try:
                name =(str(input("Enter a name: ")))
                num =input("Enter a number: ")
                telephone_dict[name] = num
                
                if name  == '':
                    print("You did not enter anything, please, try again")
                elif num == '':
                    print("You did not enter anything, please, try again")
                
            except ValueError:
                 print("Invalid Input")
                 continue
jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
tab
  • 25
  • 4
  • You need to add a break to stop the loop after the user has entered valid data. – ivvija Mar 08 '23 at 12:40
  • Does this answer your question? [Asking the user for input until they give a valid response](https://stackoverflow.com/questions/23294658/asking-the-user-for-input-until-they-give-a-valid-response) – Abdul Aziz Barkat Mar 08 '23 at 13:02

1 Answers1

0

You'll want to check if the input is valid before doing anything else. This code-block presupposes that the user input is valid and adds it to the dictionary

name =(str(input("Enter a name: ")))
num =input("Enter a number: ")
telephone_dict[name] = num

I would change it to something like

name = str(input("Enter a name: "))
num = str(input("Enter a number:" ))  # Considering the telephone_dict is `str`: `str`
if name.strip() == "" and num.strip() == "":
    continue

You might want to check the values individually so the user doesn't have to retype a valid name or num, if one or the other is invalid. The .strip() is to ensure that any whitespace is removed at the start and end of the input.

When the user inputs valid data for both variables, you add it to your dictionary and break the loop.

telephone_dict[name.strip().title()] = num.strip()
break
tim the fiend
  • 179
  • 1
  • 1
  • 9