0

I'm a python noob currently working with while loops. I get the idea about a condition has to be met for the loop to stop:

                             while some_number < 10: 

I want to use strings to stop the loop:

       continue_or_quit = str(input('Press c to continue, q to quit: ')).  

When I run this loop in the interpreter, it says variable referenced before assignment. How do I make this work?

2 Answers 2

3

Option 1 (using an infinite loop and break):

while True:
    ... # some code
    continue_or_quit = input('Press c to continue, q to quit: ')
    if continue_or_quit == 'q':
        break

Option 2 (initializing a truthy value):

continue_or_quit = 'a' # anything other than 'q'
                       # forcing the while loop to run the first time

while continue_or_quit != 'q':
    ... # some code
    continue_or_quit = input('Press c to continue, q to quit: ')

Also, you don't need to use str on input since its result is already a string.

Sign up to request clarification or add additional context in comments.

Comments

0

One thing which I noticed but won't solve your problem: In Python, the input() function will always return a string, so there is no need to cast this into a string with str().

As for your problem: With while, the loop will run as long as the condition is met. There is no need to tell the loop explicitly that it should continue. What you can do to address your need is to have the while some_number < 10: condition and then, inside the loop, ask if the user wishes to stop: continue_or_quit = input('Press q to quit: ')

You can then check if the user typed q (or Q, if you want to be case-insensitive) and, if so, break out of the loop:

while some_number < 10:
    # Do something
    continue_or_quit = input('Press q to quit: ')
    if continue_or_quit == "q" or continue_or_quit == "Q":
        break

But don't forget that some_number should change, otherwise you'll end up in a infinite loop (unless the user quits).

2 Comments

Schnitte and Mr Geek, thanks for the speedy response. I'll let you both know what works.
Schnitte, Mr Geek, here's my working code. Again, thank you both: #the loop while continue_quit == 'c': print('yo sup') #asks the user to continue or quit continue_quit = input('Press c to continue, q to quit: ')

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.