User choice menu, posibility of user choosing option using not-yet given data

Hello,

I have an exercise where the user can choose among three options, giving name, printing name, and ending the programme.

Due to the menu structure, the user can choose to print the name before the name is inputted by option 1. This leads to “NameError: name (sometexthere) is not defined”.

while (True):
    print("This programme in capable of realising the following fuctions:", "\n", "1) Give name", "\n", "2) Print name", "\n", "0) End", sep="")
    valinta = input("Give your choice: ")
    if choice == "1":
        nimi = input("Give name: ")
    elif choice == "2":
        print("Name is '", "", str(name), "", "'.", sep="")
        if name == NameError: 
            print("The name is not yet given.")
    elif choice == "0":
        print("Thank you for using this programme.")
        break
    else:
        print("Something went wrong.")  

I tried to do this in the following ways:

except ValueError:
if (emptyValueCondition):
if nameError:
if name == nameError:

except ValueError: seems to be about ensuring the user does not input data in wrong form.

Nothing seems to yet work. Thank you in advance.

while (True):
    print("Choose from the following:\n",
          "1) Give name\n",
          "2) Print name\n",
          "0) End")
    choice = input("Give your choice: ")
    if choice == "1":
        name = input("Give name: ")
    elif choice == "2":
        try:
            print(f"Name is {name}.")
        except NameError: 
            print("The name is not yet given.")
    elif choice == "0":
        print("Thank you for using this programme.")
        break
    else:
        print("Something went wrong.")

See 2. Lexical analysis — Python 3.11.1 documentation for the f-string.

An alternate choice for name is to give it a default, such as name = '<None>', before the loop so it is never missing.

1 Like

I would’ve suggested a default of None as that can never be entered by the user. Some people have unusual names…

Is your sister named “Help, I’m trapped in a driver’s license factory”?

In a GUI menu the usual way to handle this is to grey out the option.

In your code you could only output the “print” choice if you have a name already entered and you would consider 2 to be an invalid choice.