name = input("Who are you? ")
print("Are you here to test me?")
if input("y"):
print("I'll banish you " + name + ", out of this realm")
if input("n"):
print("Good. Now leave.")
I used Python in Visual Studio Code.
When executed, after I enter my name, the terminal literally says "y". I don’t want it to literally say "y". When I type anything else, the code still prints! I only want it to print when I type ‘y’ or ‘n’. Also, it’ll execute the code in the order given, not with the corresponding letter (so if I say n, it’ll give the results of y.) Please I am a beginner and I want to at least know what’s up so I can learn from my mistakes.
4
Answers
Here’s the corrected code –
Some outputs:
The
input()
function takes a single parameter, which is the prompt to show to the user. If you want to check the users input, you need to compare against the value returned by theinput()
function.You will also want to consider what happens if the user enters a response in a different case, or of a value you don’t expect.
In this example, the response to the second prompt is immediately converted to lowercase, and then we take only the first character to use for the comparison. I’ve also added a branch to handle if the user input isn’t ‘y’ or ‘n’.