0

I can't figure out how to add a while loop to keep asking for a name until the user types quit.

I've tried different while syntax but the closest thing I've gotten is what you see my code as. I just started coding so I'm a novice.

name = input('Enter your name, or type quit to exit ')
keep_going = True
while keep_going:
    if name == "quit":
        keep_going = False

At the start of the program anything I enter lets me in, which is not supposed to happen. What should be happening is entering any name should let me in, and typing "quit" should keep prompting me for a new answer.

The process is flipped at the end of my code too... If I type "quit" it starts the program and if I type any other name it ends the program for the final step of my coding. Which is... Step 7: add an input statement to enter name or type quit to exit

Jmonsky
  • 1,519
  • 1
  • 9
  • 16
Malakaizer
  • 1
  • 1
  • 1
  • 1

3 Answers3

0

You need to put the input into the loop. Also exiting the loop continues execution of the program and does not quit the program. You can use sys.exit() to do so.

I am not sure what you count as a name, but in this example it is any word at least 1 letter long. Then typing 'quit' (not case sensitive because I call .lower() on the string) exits the program.

import sys
name = ""
while len(name) > 0: # user must enter a name at least 1 character long to proceed
    name = input('Enter your name, or type quit to exit ')
    if name.lower() == "quit":
        sys.exit() # when the user enters exit, exit the program

If you have a function that defines what a name is or is not: validName(name), you could also do:

while not validName(name):
Jmonsky
  • 1,519
  • 1
  • 9
  • 16
0

Try this code:

name = input('Name: ')

if name == 'quit':
    keep_going = False
else:
    keep_going = True
# other code...
JonPizza
  • 129
  • 1
  • 11
0

Currently, you ask the question once and then enter the loop. By typing 'quit', you exit the loop but if you do not type quit, the loop is infinite as there is no opportunity for the user to enter a new name. There fore, you need to put your input statement inside the while loop so the question is continually repeated and answered.

keep_going = True
while keep_going:
     name = input('Enter your name, or type quit to exit ')
     if name == "quit":
        keep_going = False