-4

This is my code I am a new to Python, it repeats even if you Type "Y" and it doesn't exit the program when typing "N". Thanks in Advance, forgive my indentation errors if I type in Y it just repeats the code/ question when using Break and when typing in N the code ends but the program doesn't exit:

while True:
    answer = input("Would You Like To Play?")
    if answer == "Y":
        print("good luck")
    elif answer == "N":
        exit()    
Undo
  • 25,519
  • 37
  • 106
  • 129
Fishhy
  • 35
  • 1
  • 7
  • _"forgive my errors"_. If you mean, forgive the incorrect indentation, I'd prefer you just fix it rather than leave it broken and apologize about it. Meet us halfway please. – Kevin Jul 24 '15 at 16:37
  • Tell us the exact error please. – Meghdeep Ray Jul 24 '15 at 16:38
  • What are you expecting your code to do when the answer is "Y" and "N" respectively? – user3885927 Jul 24 '15 at 16:43
  • 1
    For your "N" part you should use sys.exit() Read this for more info: http://stackoverflow.com/questions/6501121/the-difference-between-exit-and-sys-exit-in-python – user3885927 Jul 24 '15 at 16:45
  • if a user types "y" in it should continue the rest of the code which carries on to asking the users name but if the user types "N" the program should end – Fishhy Jul 24 '15 at 16:46
  • Thank you all for your help!!! – Fishhy Jul 24 '15 at 16:51

1 Answers1

1

You have to escape the loop, with while True: it will always indefinitely execute unless you exit the loop with a break or an exit().
A better practice however, is using a Boolean value as a loop control variable and changing it when you need to. That will break the loop.

This will work :

flag = True
while flag:
    answer = input("Would You Like To Play?")
    if answer == "Y" or answer == "y":
        print("good luck")
        #do whatever you want to here
        flag = False 
    elif answer == "N" or answer =="n":
        flag = False


Also in your code the indentation was wrong, I edited it so it's alright now, check your indentation because indentation matters a lot in terms of control flow. That might fix it.

Meghdeep Ray
  • 5,262
  • 4
  • 34
  • 58
  • thank you for your code however when typing "Y" it just repeats the question – Fishhy Jul 24 '15 at 16:43
  • because you had while at the start, you have to escape the loop, either by `break` or exit(), using a flag is a better control structure, since you have `while True:` it will always loop indefinitely until you manually break the loop. Using flags is better here as I changed the answer to reflect. – Meghdeep Ray Jul 24 '15 at 16:45