user11605169
user11605169

Reputation:

While loop displaying correct answer as incorrect

So the while loop is supposed to make the user enter one of the two available choices (y/n) but if i input anything, it is shown as incorrect.

I have tried changing the ! to a = and some other minute things but that has done nothing.

print("Hello there " + str(name) + ", are you ready for your 
adventure? Y/N")
    adventure = input()
    while adventure.lower() != "y" or "n":
        print(str(name) + " ,that's not a choice. I'll ask again, are 
you ready for your adventure? Y/N")
        adventure = input()
    if adventure.lower() == "n":
        print("Cowards take the way out quickly.")
        breakpoint
    else:
        print("Come, you will make a fine explorer for the empire!")

It isn't a syntax error but it is a logic error.

Upvotes: 1

Views: 64

Answers (1)

blackbrandt
blackbrandt

Reputation: 2095

Change your if statement to:

print("Hello there " + str(name) + ", are you ready for your 
adventure? Y/N")
adventure = input()
while adventure.lower() not in ("y", "n"): # <<<<<---- This line changed

    print(str(name) + " ,that's not a choice. I'll ask again, are 
you ready for your adventure? Y/N")
    adventure = input()
    if adventure.lower() == "n":
        print("Cowards take the way out quickly.")
        breakpoint
    else:
        print("Come, you will make a fine explorer for the empire!")

This is due to how comparisons are done in Python3. See here

Some other fixes you can make to your code:


adventure = input("Hello there {}, are you ready for your adventure? Y/N".format(name)) #Added prompt to input, using string formatting. 

while adventure.lower() not in ("y", "n"): # <<<<<---- Check input against tuple, instead of using `or` statement

    adventure = input(" {}, that's not a choice. I'll ask again, are you ready for your adventure? Y/N".format(name)) #Same as first line
    if adventure.lower() == "n":
        print("Cowards take the way out quickly.")
        break
    else:
        print("Come, you will make a fine explorer for the empire!")

See usage of python input command, string formatting

Upvotes: 1

Related Questions