There are a couple of bugs unrelated to your main question:
("(input name), that's a nice name.")
doesn't do variable interpolation. You can use an f-string print(f"{name}, that's a nice name.")
if Name == 'Cher' or 'Madonna':
won't work as you think because the condition is always true. It evaluates as if (Name == 'Cher') or ('Madonna'):
and the nonempty string 'Madonna'
is always truthy. if name in ["Cher", "Madonna"]:
fixes the job by checking list membership. if name == "Cher" or name == "Madonna":
also works.
The overall flow you want isn't entirely clear -- I assume the second while
loop wasn't intended, because it'd be strange to prompt a user until their name changes or they have to guess "Madonna"
or "Cher"
to make progress.
In any case, my recommendation is to abstract out the idea of "asking the user for input until they give an appropriate response". This makes it much simpler to validate input and get rid of the loop and block necessary to do so in your main line code.
For example,
def get_response(prompt, error_message=None, predicate=bool):
while True:
response = input(prompt)
if predicate(response):
return response
if error_message is not None:
print(error_message)
def main():
get_response(
prompt="Enter Password: ",
error_message="Password did not match!",
predicate=lambda x: x == "hello"
)
print("Login successful!")
print("Welcome to the second half of the program")
name = get_response(
prompt="What is your name? ",
error_message="At least one character needed!"
)
if name in ["Cher", "Madonna"]:
print("May I have your autograph, please?")
else:
print(f"{name}, that's a nice name.")
if __name__ == "__main__":
main()
Sample run:
Enter Password: blah
Password did not match!
Enter Password: hello
Login successful!
Welcome to the second half of the program
What is your name?
At least one character needed!
What is your name?
At least one character needed!
What is your name? blarrghg
blarrghg, that's a nice name.
As you add complexity and begin adding branches and tracking state, for example, whether the user's name is "Madonna"
or "Cher"
or something else that can influence future questions, you might want to look into a decision tree or state machine (nice if states can be reached from multiple locations or are repeatable, like re-entering a room).
Without care, you can wind up with tons of nested if
/elif
/else
which will make the code unpleasant, even if they're buried in many functions.
I'm probably getting ahead of myself though.